问题
I'm trying to override a JS function named replaceMe
in the web page from my add-on's content script, but I see that the original function implementation always gets executed.
Original HTML contains the following function definition:
function replaceMe()
{
alert('original');
}
I'm trying to override it my add-on like (main.js
):
tabs.activeTab.attach({
contentScriptFile: self.data.url("replacerContent.js")
});
Here's what my replacerContent.js
looks like:
this.replaceMe = function()
{
alert('overridden');
}
However, when I run my addon, I always see the text original
being alerted, meaning the redefinition in replacerContent.js never took effect. Can you let me know why? replaceMe
not being a privileged method, I should be allowed to override, eh?
回答1:
This is because there is an intentional security between web content and content scripts. If you want to communicate between web content and you have control over the web page as well, you should use postMessage.
If you don't have control over the web page, there is a hacky workaround. In your content script you can access the window object of the page directly via the global variable unsafeWindow
:
var aliased = unsafeWindow.somefunction;
unsafeWindow.somefunction = function(args) {
// do stuff
aliased(args);
}
There are two main caveats to this:
- this is unsafe, so you should never trust data that comes from the page.
- we have never considered the
unsafeWindow
hack and have plans to remove it and replace it with a safer api.
回答2:
Rather than relying on unsafeWindow
hack, consider using the DOM.
You can create a page script from a content script:
var script = 'rwt=function()();';
document.addEventListener('DOMContentLoaded', function() {
var scriptEl = document.createElement('script');
scriptEl.textContent = script;
document.head.appendChild(scriptEl);
});
The benefit of this approach is that you can use it in environments without unsafeWindow
, e. g. chrome extensions.
You can then use postMessage or DOM events to communicate between the page script and the content script.
来源:https://stackoverflow.com/questions/22725555/override-web-pages-javascript-function-using-firefox-addon-sdk