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

Firefox WebExtensions send message from browser to extension and get response in call back function

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

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