0

This fantastic answer shows how you can dynamically insert JavaScript into a page from a Chrome extension:

var s = document.createElement('script');
// TODO: add "script.js" to web_accessible_resources in manifest.json
s.src = chrome.extension.getURL('script.js');
s.onload = function() {
    this.parentNode.removeChild(this);
};
(document.head||document.documentElement).appendChild(s);

When the onload() function is called, it's executed in the browser page's isolated world, not the extension's isolated world, right?

Assuming that's correct, I'm having an problem I don't understand.

Inside of my script.js I have code similar to this:

var globalObj = globalObj || {};
globalObj.method = function () {
    console.log('hey!');
};

Then I changed the onload() function above to:

s.onload = function() {
    this.parentNode.removeChild(this);

    globalObj.method();
};

But the console shows the error:

Uncaught ReferenceError: globalObj is not defined

Why isn't globalObj defined inside of the onload() function?

Community
  • 1
  • 1
Nate
  • 26,164
  • 34
  • 130
  • 214

1 Answers1

1

onload executes in the content script context, and not in the page context.

To communicate between page context and script context, you can use various methods; for example, a custom DOM event will achieve what you need here:

// Content script
s.onload = function() {
  this.parentNode.removeChild(this);
  var event = new CustomEvent("invokeMethod");
};

// script.js
window.addEventListener("invokeMethod", function(evt) {
  globalObj.method();
}, false);
Xan
  • 74,770
  • 16
  • 179
  • 206