首页 > 解决方案 > Google 登录,在使用 ReactJS 的扩展中 - 错误无法读取未定义的属性“加载”

问题描述

我正在尝试使用 ReactJS 在扩展程序中创建 Google 登录,但我不断收到以下错误:

无法读取未定义的属性“负载”

我不知道我是否做得对,任何人都可以帮助我。这是我第一次构建扩展。

登录组件如下:

function Login() {

const gapi = window.gapi;
const [isLoggedIn, setLoggedIn] = useState(false);

const signUpWithGoogle = () => {
    gapi.load("client:auth2", () => {
        gapi.client.init({
            apiKey: API_KEY,
            clientId: CLIENT_ID,
            discoveryDocs: DISCOVERY_DOCS,
            scope: SCOPES,
        })
        gapi.auth2.getAuthInstance().signIn()
        .then( () => {
            setLoggedIn(true);
        })
    });
}

const signoutWithGoogle = () => {
    gapi.auth2.getAuthInstance().signOut()
    .then( () => {
        setLoggedIn(false);

    })
};

return (
    <div className="app">
        {isLoggedIn ? (
            <div className="Home">
                <div className="homeHeading">
                    <h3>Schedule Meetings</h3>
                    <button onClick={signoutWithGoogle}>Logout</button>
                </div>
                <Home />
            </div>
        ) : (
            <div>
                <section className="login">
                    <header className="loginHeading">
                        <h1>Welcome to Google Meet</h1>
                    </header>
                    <button
                        onClick={signUpWithGoogle}
                        type="button"
                    >
                        Login with Google
                    </button>
                </section>
            </div>
        )}
    </div>
);}

我在 manifest.json 中提到了 CSP

{  "manifest_version": 2,
  "name": "Schedule Meetings",
  "description": "App to Schedule Meetings",
  "version": "1.0",

  "browser_action": {
    "default_popup": "index.html",
    "default_title": "Open to Schedule the meetings"
  },
"content_security_policy": "script-src 'self' https://apis.google.com/js/api.js; object-src 'self'" }

在 HTML 文件中,我已将脚本 src 添加到 background.js。执行此步骤修复了内联脚本冲突。

    <script src="./background.js" type="text/javascript"></script>

background.js 文件如下

 var head = document.getElementsByTagName('head')[0];
 var script = document.createElement('script');
 script.type = 'text/javascript';
 script.src = "https://apis.google.com/js/api.js";
 head.appendChild(script);

谢谢你。

标签: reactjsgoogle-chrome-extensiongoogle-signin

解决方案


推荐阅读