3

I need to extend the Audio object to provide a stop function. Normally this code would work:

Audio.prototype.stop = function() {
    this.pause();
    this.currentTime = 0;
}

However, I need this to happen from within a content script of a Chrome Extension, and as the contexts are separate the change does not propagate to the other context.

I have tried using this unsafeWindow hack to attempt to break out of the isolated environment, with no success, as well as attempting to use Object.create and set the constructor property.

Adam M-W
  • 3,509
  • 9
  • 49
  • 69
  • 1
    The page's global `window` object is never accessible to a Content script. The problem is a duplicate of [Building a Chrome Extension - Inject code in a page using a Content script](http://stackoverflow.com/questions/9515704/building-a-chrome-extension-inject-code-in-a-page-using-a-content-script). Side note, I'd use `if (!Audio.prototype.stop) ...;`, to avoid conflicts when `stop` is implemented. – Rob W Jul 17 '12 at 10:38

1 Answers1

0

The content script has an isolated execution environment, but it shares the DOM with the page. You can run a script in the actual execution environment of the page by adding a <script> tag to the DOM:

var s = document.createElement("script");
s.innerText = "Audio.prototype.stop = function() { this.pause(); this.currentTime = 0; }";
document.documentElement.appendChild(s);

I believe this code will run the script in both execution environments (or, at the very least, it should run in the page's environment).

Note that this solution can only run script during or after resource-load time, not as soon as the DOM is complete, since it requires the browser to process the new script resource being added to the page. That shouldn't be a problem for your current needs.

apsillers
  • 112,806
  • 17
  • 235
  • 239