gpt4 book ai didi

javascript - Firefox WebExtensions 将消息从浏览器发送到扩展并在回调函数中获得响应

转载 作者:行者123 更新时间:2023-11-29 14:39:49 24 4
gpt4 key购买 nike

我正在尝试将我的 Chrome 扩展程序转换为 FireFox WebExtensions 。我在我的网页与后台脚本之间进行通信时遇到问题。从内容脚本中,我将一些功能注入(inject)浏览器页面。该功能需要调用浏览器扩展并获得响应。

manifest.json

{
"manifest_version" : 2,
"name" : "Sample",
"description" : "Sample",
"version" : "1.0",

"icons" : {
"48" : "icons/link-48.png"
},

"applications" : {
"gecko" : {
"id" : "sample@sss.com",
"strict_min_version" : "48.0"
}
},

"permissions" : ["notifications", "alarms", "storage"],

"background" : {
"scripts" : [
"js/jquery.js",
"background-script.js"
]

},
"web_accessible_resources" : ["js/content.js"], // Not working in firefox
"externally_connectable" : {
"matches" : [
"http://localhost/*",]
},
"content_scripts" : [{
"matches" : ["<all_urls>"],
"js" : ["js/jquery.js",
"js/script.js",
"content-script.js"
],
"run_at" : "document_start"
}
],
"default_locale" : "en"
}

content-script.js

var port = chrome.runtime.connect();

window.addEventListener("message", function(event) {

if (event.source != window)
return;

if (event.data.type && (event.data.type == "FROM_PAGE")) {
console.log("Content script received: " + event.data.text);
chrome.runtime.sendMessage({
hello: 1
},function (response)
{
//Need to send response back to browser
});
}
}, false);

background-script.js

chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
alert('bg');
var response_Text = '-1';

if (request.hello) {
console.log('hello received');
sendResponse("213");
}
});

browser page

window.postMessage({ type: "FROM_PAGE", text: "Hello from the webpage!" },"*");

我正在使用 window.postMessage 发送一些内容。

是否可以获得此函数的回调值或任何可用于从网页向扩展程序发送消息并获得响应的方法?

最佳答案

Browser Page

将您的回调转换为字符串并附加详细参数

var callbackstring=callback.toString(); *

然后点赞

var evt = document.createEvent("CustomEvent");
evt.initCustomEvent("eventname", true, true, {callback:callbackstring});
window.dispatchEvent(evt);

Content Script

从事件对象中检索回调字符串

var callbackstring=event.detail.callback;

使用eval函数并将字符串转换为函数

eval("var callback="+callbackstring);

现在您可以在监听器中轻松触发您的回调

callback(response);

关于javascript - Firefox WebExtensions 将消息从浏览器发送到扩展并在回调函数中获得响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40156230/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com