Override web page's javascript function using firefox addon sdk

余生长醉 提交于 2019-12-23 02:04:18

问题


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:

  1. this is unsafe, so you should never trust data that comes from the page.
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!