简体   繁体   English

如何从Firefox扩展名执行网页名称空间(范围)中的javascript代码?

[英]How to execute javascript code in the namespace (scope) of the webpage, from a firefox extension?

I'm looking for a clean way to call/execute/redefine javascript code from a webpage, within firefox, through a firefox extension. 我正在寻找一种干净的方法来通过firefox扩展从firefox中的网页调用/执行/重新定义javascript代码。 My temporary solution is to use the scratchpad (Shift-F4, Ctrl-A, Ctrl-V, Ctrl-R), it works fine but is a sad work-around. 我的临时解决方案是使用暂存器(Shift-F4,Ctrl-A,Ctrl-V,Ctrl-R),它可以正常工作,但很可悲。 Greasemonkey would be my last resort, very very last. Greasemonkey将是我的最后选择,非常非常最后。

Here' the code so far: 到目前为止的代码:

main.js: main.js:

exports.main = function() {
  var data = require("self").data;
  var pageMod = require("page-mod");
  pageMod.PageMod({
    include: "*.google.com",
    contentScriptFile: data.url("my-script.js")
  });
};

my-script.js 我-的script.js

$('#mydiv').html('yo')
alreadyHere.sayHello=function (){alert('Bonjour');}


This code halts on line #1 of my-script.js saying that $ is not defined. 此代码在my-script.js的#1行暂停,提示未定义$。 Problem of namespace/scope. 名称空间/范围的问题。

How can I work within the namespace/scope of the webpage, from my extension, like I do with the scratchpad? 我如何从扩展名开始在网页的命名空间/范围内工作,就像在便签本上一样?

Edit: There should be a link between window.content of the firefox main window and alreadyHere.sayHello from the webpage, no? 编辑: firefox主窗口的window.content和网页中的Here.sayHello之间应该存在链接,对吗?

window.content.(things).alreadyHere.sayHello();

What am I missing here? 我在这里想念什么?

HELL YEAH. 地狱呀。

window.content.document.defaultView.wrappedJSObject.$('#mydiv').html('yo')
window.content.document.defaultView.wrappedJSObject.alreadyHere.sayHello();

Thanks Mridang Agarwalla here 感谢Mridang Agarwalla 在这里

Did you tried in Firebug console? 您是否在Firebug控制台中尝试过?

And also, 并且,

Make sure you code is within 确保您的代码在

$(document).ready(function () {
  //your code here
});

and most important jQuery is properly loaded 最重要的jQuery已正确加载

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM