如何在Firefox Web扩展中使用cloneInto? [英] How to use cloneInto in a Firefox web extension?
问题描述
我正在尝试编写一个Web扩展,我需要将对象从内容脚本传递到页面脚本.除其他外,我看过 https://developer.mozilla.org/zh-CN/Add-ons/WebExtensions/Content_scripts#Sharing_content_script_objects_with_page_scripts 和 然后在页面脚本中,这个: 当我将其粘贴到自己的扩展名中时,当它到达页面脚本中的上一行时,将报告错误:TypeError:window.messenger未定义. 我不知道该如何解决.有什么想法吗?还是有更好的方法与页面脚本共享内容脚本中的对象? 我找到了替代解决方案.我没有解决如何使用cloneInto的问题,但是现在可以通过使用 内容脚本: 页面脚本: 此方法的优点是它不使用特定于Firefox的功能. https://developer.mozilla.org/zh-CN/附加组件/WebExtensions/API/runtime/sendMessage https://developer.mozilla.org/zh-美国/附加组件/WebExtensions/API/运行时/onMessage I am trying to write a web extension where I need to pass an object from the content script to the page script. I have looked at, among others, https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Content_scripts#Sharing_content_script_objects_with_page_scripts and https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Language_Bindings/Components.utils.cloneInto I want to use the cloneInto function described there. There is a code example that looks like this: Then in the page script, this: When I paste this into my own extension, by the time it gets to the above line in the page script an error is reported: TypeError: window.messenger is undefined. I cannot figure out how to solve this. Any thoughts? Or is there a better way to share an object from the content script with the page script? I found an alternative solution. I didn't solve the question of how to use cloneInto but I am able to pass objects to my page script now, by using Content script: Page script: An advantage of this approach is that it doesn't use Firefox-specific functions. https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/runtime/sendMessage
https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/runtime/onMessage 这篇关于如何在Firefox Web扩展中使用cloneInto?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
window.messenger.notify(来自页面脚本的消息!");
sendMessage
并创建 onMessage
侦听器将对象传递给我的页面脚本.>
browser.runtime.sendMessage({theBlobs:myBlobObjects});
browser.runtime.onMessage.addListener(function(request,sender,sendResponse){var blobs = request.theBlobs;对于(var i = blobs.length-1; i> = 0; i--){//用Blob做聪明的事}}
// this happens in the content script
var messenger = {
notify: function(message) {
browser.runtime.sendMessage({
content: "Object method call: " + message
});
}
};
window.wrappedJSObject.messenger = cloneInto(
messenger,
window,
{cloneFunctions: true});
window.messenger.notify("Message from the page script!");
sendMessage
and creating an onMessage
listener. browser.runtime.sendMessage({theBlobs: myBlobObjects});
browser.runtime.onMessage.addListener(function(request, sender, sendResponse) {
var blobs = request.theBlobs;
for (var i = blobs.length - 1; i >= 0; i--) {
// do clever things with the blobs
}
}