Dev.K.
Dev.K.

Reputation: 2488

Chrome Extension Call Function from Injected Script

I've injected two .js files (Let' say for example a.js and b.js ) into a web page using content script, using technique mentioned here:

Access window variable from Content Script

function injectScript(file, node) {
    var th = document.getElementsByTagName(node)[0];
    var s = document.createElement('script');
    s.setAttribute('type', 'text/javascript');
    s.setAttribute('src', file);
    th.appendChild(s);
}
injectScript( chrome.extension.getURL('/js/my_file.js'), 'body');

Both script injections are successful. Now 'a.js' has a function called FuncA(){}. Now when I'm trying to call FuncA() from b.js I'm getting following error.

b.js:6 Uncaught ReferenceError: FuncA is not defined

Upvotes: 0

Views: 1022

Answers (2)

Xan
Xan

Reputation: 77523

A proper way of handling this is to rely on callbacks, not arbitrary timeouts.

function injectScript(file, node, callback) {
    var th = document.getElementsByTagName(node)[0];
    var s = document.createElement('script');
    s.setAttribute('type', 'text/javascript');
    s.setAttribute('src', file);
    if (typeof callback == "function") {
      s.onload = function() { callback(); };
    }
    th.appendChild(s);
}

injectScript( chrome.extension.getURL('/js/a.js'), 'body', function() {
  injectScript( chrome.extension.getURL('/js/b.js'), 'body');
});

With an arbitrarily chosen 500ms delay you run the risk of either waiting too long, or not waiting enough in some extreme case. By relying on onload event for the script tag, you know exactly when it has finished executing.

Upvotes: 3

Dev.K.
Dev.K.

Reputation: 2488

The problem is resolved. The first script I was injecting was very big. So somehow the injection was not getting completed and I was calling the function. Hence I added some delay.

injectScript( chrome.extension.getURL('/js/a.js'), 'body');
setTimeout(function(){
    injectScript( chrome.extension.getURL('/js/b.js'), 'body');
}, 500);

Upvotes: 0

Related Questions