Google Sign-in, in an extension using ReactJS - error Cannot read property 'load' of undefined

Viewed 74

I'm trying to create a Google Sign-in in an extension using ReactJS, but I keep getting the following error:

Cannot read property 'load' of undefined

I don't know if I'm doing it right, Can anyone help me out. This is the first time I'm building an extension.

Login component is as follows:

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>
);}

I have mentioned CSP in the manifest.json

{  "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'" }

In the HTML file, I have added the script src to background.js. Doing this step fixed the inline script violation.

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

background.js file is as follows

 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);

Thank you.

0 Answers
Related