Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to load the Google APIs client library inside my index.html and the onLoad='someMethod' will invoke a method in a separate javascript file. That method will then print out to the console.

The client library is loaded without any problems but the message is not getting printed out the console and I think it's because the method is not getting invoked at all.

Here is my index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Welcome</title>

    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
</head>

<body>
    <div id="app"></div>
    <script src="lib/vendors.js"></script>
    <script src="build/bundle.js"></script>
    <script src="https://apis.google.com/js/client.js?onload=handleGoogleClientLoad"></script>
</body>

Here is the javascript file that contains the handleGoogleClientLoad method:

import React from 'react';
import ReactDOM from 'react-dom';

import {Button} from 'react-bootstrap';

class MyApp extends React.Component {

handleGoogleClientLoad() {
    console.log('Success on load');
}

render() {
    return (
        <div>
            <Button>Click Me</Button>
        </div>
    );
  }
}


const app = document.getElementById('app');

ReactDOM.render(<MyApp />, app);

If this was plain javascript the method would look like this:

window.handleGoogleClientLoad = function() {
  // Log to the console
};

Is there anything in es6 that is similar to the window object.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
222 views
Welcome To Ask or Share your Answers For Others

1 Answer

Component methods are not attached to the window object. MyApp.handleGoogleClientLoad is not going to be aliased to window.handleGoogleClientLoad which is what the google API script is likely trying to invoke.

If you want the Google API to call a method on your component you're going to have some trouble as there's no guarantee that your component will be mounted before or after your Google API script loads. If you want to guarantee that you'd have to inject the script after the component mounted and register the function in the componentDidMount method. You can use something like loadjs

componentDidMount() {
 window.handleGoogleClientLoad = function() {
  // log to console
 }
 loadjs('https://apis.google.com/js/client.js?onload=handleGoogleClientLoad')
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...