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.

4

1 回答 1

0

内容脚本有一个独立的执行环境,但它与页面共享 DOM。您可以通过在 DOM 中添加标签来在页面的实际执行环境中运行脚本:<script>

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

我相信这段代码将在两个执行环境中运行脚本(或者,至少它应该在页面环境中运行)。

请注意,此解决方案只能在资源加载期间或之后运行脚本,而不是在 DOM 完成后立即运行,因为它需要浏览器处理添加到页面的新脚本资源。对于您当前的需求,这应该不是问题。

于 2012-07-16T20:03:07.857 回答