使用firefox addon sdk覆盖网页的javascript功能 [英] Override web page's javascript function using firefox addon sdk

查看:129
本文介绍了使用firefox addon sdk覆盖网页的javascript功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从我的附加组件的内容脚本中覆盖一个名为 replaceMe 的JS函数,但是我发现原来的函数实现总是被执行。
$ b 原始的HTML包含以下函数定义:

  function replaceMe ()
{
alert('original');

$ / code>

我试图覆盖它像我的插件像(<$ c
$ b

  tabs.activeTab.attach({
contentScriptFile:self.data.url(replacerContent.js)
});

以下是我的 replacerContent.js 的样子:

$ p $ this.replaceMe = function()
{
alert('overridden');





$ b

然而,当我运行我的插件时,我总是看到 original 被警告,这意味着replacerContent.js中的重定义从未生效。你能让我知道为什么吗? replaceMe 不是特权方法,我应该被允许重写,呃?

解决方案

这是因为有网页内容和内容脚本之间的有意安全。如果您想在网页内容之间进行交流,并且您也可以使用postMessage。



如果您无法控制网页,有一个hacky的解决方法。在您的内容脚本中,您可以通过全局变量 unsafeWindow 直接访问页面的窗口对象:

  var aliased = unsafeWindow.somefunction; 

unsafeWindow.somefunction = function(args){
// do stuff
aliased(args);

$ / code $ / pre

有两个主要的注意事项:


  1. 这是不安全的,所以您不应该信任来自页面的数据。

  2. 我们从来没有考虑过 unsafeWindow hack并计划删除它,并用更安全的api替换它。


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?

解决方案

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.

这篇关于使用firefox addon sdk覆盖网页的javascript功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆