简体   繁体   English

Firefox附加组件:从选项卡获取文档

[英]Firefox Add-on: get document from a tab

I was just trying to get the document of a tab and read information from it, but if I try to read the information on the Add-on-side I get an error "doc.getElementById is not a function". 我只是试图获取选项卡的文档并从中读取信息,但是如果尝试读取附加组件上的信息,则会收到错误消息“ doc.getElementById不是函数”。 In the content-script it works fine. 在内容脚本中,它可以正常工作。 So is there a problem with passing whole objects through self.port? 那么通过self.port传递整个对象是否有问题?

var tabs = require('sdk/tabs');
var myTab;
var myScript = "self.port.on('getDocument', function() {" +
               "  var doc = window.document;" +
               "  console.log(doc.getElementById('lga').style.height);" +
               "  self.port.emit('answer', doc);" +
               "})";

for each (var tab in tabs) {
    if (tab.url == "https://www.google.com/") {
        myTab = tab;
    }
}

worker = myTab.attach({
    contentScript: myScript 
});

worker.port.emit("getDocument");

worker.port.on("answer", function(doc) {
  console.log(doc.getElementById('lga').style.height);
});

You can only pass values via a message that could be serialized to JSON. 您只能通过可以序列化为JSON的消息传递值。 doc , being a document, cannot be passed. doc是文档,无法传递。

In your message, you could pass the actual value of the style instead: 在您的消息中,您可以改为传递样式的实际值:

self.port.emit('answer', doc.getElementById('lga').style.height);

Rather than try to import the document into main.js , create a new Javascript file in the data folder, ContentScript.js . 与其尝试将文档导入到main.jsmain.jsdata文件夹ContentScript.js创建一个新的Javascript文件。 Inject it with contentScriptFile into the page like so: contentScriptFile将其注入页面,如下所示:

worker = myTab.attach({
    contentScriptFile: require('sdk/self').data.url('ContentScript.js')
});

Meanwhile, in ContentScript.js 同时,在ContentScript.js中

var doc = window.document;
//Now have your way with the document

Then if you ever need any variables in main.js, do what @nmaier said. 然后,如果您在main.js中需要任何变量,请执行@nmaier所说的。

I realize that this may be obvious, but this is the intended behaviour, and it means you don't have to write a script as a string and provides more detailed logging. 我意识到这可能很明显,但这是预期的行为,这意味着您不必将脚本编写为字符串即可提供更详细的日志记录。

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

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