2016-06-30 3 views
4

私のChrome拡張機能をFireFoxアドオンに変換しようとしています。私が今抱えている唯一の問題は、私のウェブページとバックグラウンドスクリプトとの間のやり取りです。Firefoxアドオン - Webページからバックグラウンドスクリプトにメッセージを送信

はクロームでは、これは私がやったことです:私はonMessageExternalはまだFirefoxでサポートされていないことがわかりました

chrome.runtime.sendMessage(ChromeExtId, {hello: 1}); 

background.js

chrome.runtime.onMessageExternal.addListener(function(request) 
{ 
    if (request.hello) { console.log('hello received'); } 
}); 

Webページ、私は今この状況をどのように処理するのか完全に迷っています。

ご協力いただければ幸いです。

+1

あなたが達成しようとしているもの - Firefox ** Add-on **、またはFirefox WebExtension? – Xan

答えて

3

コンテンツスクリプトを使用して、Webページからbackground.jsと通信できます。これを試してみてください:

background.js

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) { 
     if (request.hello) { 
      console.log('hello received'); 
     } 
    }); 

コンテンツスクリプト

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 
     }); 
    } 
}, false); 

Webページへなど、いくつかの混乱があるようです

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

私はそのコードを取得してい全ては、次のとおりにReferenceError - クロムが定義されていない。chrome.runtime.sendMessage(ChromeExtId、{こんにちは:1}); – Dave

+0

マニフェストファイルを共有してください。firefoxのchrome.runtime.sendMessageの代わりにbrowser.runtime.sendMessageを使用してください。 – sweeta

+0

Downvoting - [外部との通信の仕組み](https://developer.chrome.com/extensions /メッセージング#外部 - ウェブページ)。 – Xan

関連する問題