我試圖將我的Chrome擴展轉換爲FireFox WebExtensions。我有一個問題,我的網頁與後臺腳本之間進行通信。 從內容腳本我正在注入一些功能到瀏覽器頁面。該功能需要調用瀏覽器擴展並獲得響應。Firefox WebExtensions從瀏覽器發送消息到擴展並獲得回調函數
的manifest.json
{
"manifest_version" : 2,
"name" : "Sample",
"description" : "Sample",
"version" : "1.0",
"icons" : {
"48" : "icons/link-48.png"
},
"applications" : {
"gecko" : {
"id" : "[email protected]",
"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"
}
內容的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);
背景的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");
}
});
瀏覽器頁面
window.postMessage({ type: "FROM_PAGE", text: "Hello from the webpage!" },"*");
我使用window.postMessage發送一些內容。
是否可以獲取該函數的回調值或任何可用的方法從網頁發送消息到擴展並獲得響應?
請將該問題置於主題上:包括一個可以複製問題的完整** [mcve]。通常包括一個* manifest.json *,一些背景*和*內容腳本。尋求調試幫助的問題(「**爲什麼不是這個代碼工作?」)必須包括:►期望的行爲,►特定問題或錯誤*和*►在問題中重現問題所需的最短代碼**本身**。沒有明確問題陳述的問題對其他讀者無益。請參閱:「**如何創建[mcve] **」,[我可以在此處詢問哪些主題?](http://stackoverflow.com/help/on-topic)和[問]。 – Makyen
添加了更多信息 –
感謝您提供信息。但是,我們確實需要* manifest.json *文件。該文件定義了擴展的許多方面。它包含通常需要的信息來確定擴展名正在發生什麼。我們還需要爲瀏覽器頁面中的代碼提供更多的上下文。何時以及如何將該行代碼包含在頁面中並運行?理想情況下,您將包括複製問題所需的一切。對於您直接從問題中直接複製代碼(並且不加任何其他內容)以查看它是否重複該問題通常是一個好主意。 – Makyen