使用firefox插件sdk覆盖网页的javascript函数 [英] Override web page's javascript function using firefox addon sdk

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

问题描述

我正在尝试从附加组件的内容脚本中覆盖网页中名为 replaceMe 的JS函数,但是我看到原始函数的实现总是被执行.

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.

原始HTML包含以下函数定义:

Original HTML contains the following function definition:

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

我正在尝试覆盖其插件,例如( main.js ):

I'm trying to override it my add-on like (main.js):

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

这是我的 replacerContent.js 的样子:

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

但是,当我运行插件时,总是会看到文本原始处于警报状态,这意味着对replacerContent.js的重新定义从未生效.你能让我知道为什么吗? replaceMe 不是特权方法,应该允许我覆盖,是吗?

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?

推荐答案

这是因为Web内容和内容脚本之间存在故意的安全性.如果要在Web内容之间进行通信并且也可以控制Web页面,则应使用postMessage.

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.

如果您无法控制网页,则可以使用变通方法.在内容脚本中,您可以直接通过全局变量 unsafeWindow :

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);
}

对此有两个主要警告:

  1. 这是不安全的,因此您永远不要信任来自页面的数据.
  2. 我们从未考虑过 unsafeWindow 黑客,并计划删除它并用更安全的api代替.
  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插件sdk覆盖网页的javascript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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