2016-03-29 3 views
0

にバックグラウンドスクリプトにアクセスすることができ、私はWebExtension(Firefoxの下にそれらを使用しようとしている)とは全く新たなんです。私はブラウザアクションを書いた。永続的な状態を維持するために、私はバックグラウンドスクリプトを実装しなければならないと考えました。WebExtension:どのように私は私のブラウザのアクション

どのように私は私のブラウザアクションスクリプトからバックグラウンドスクリプトで定義された変数をacccessことができますか?

や背景スクリプトは、ブラウザのアクションの状態を含めることができるという前提が間違っているのですか?

答えて

1

よろしくお願いします。私は良いスタートを見つけたherehere

私は、ブラウザアクションとバックグラウンドスクリプト間の通信のためのメッセージの投稿を使用しています。あなたは、ブラウザアクションポップアップやゲーム状態で機能することができ、ゲームの

だと思うが、バックグラウンドスクリプトです。ここでは、ブラウザアクションにバックグラウンドスクリプトからコインの枚数(プレイヤーのお金を)取得するための例です:

ブラウザアクション:

var _playerCoins = 0; 

// I connect a 'port' with the name 'getCoins'. 
var _port = chrome.runtime.connect({name: "getCoins"}); 

// This is the message that is called if the other side posts a message via the port. 
// The background script puts the current amount of coins into the message 
_port.onMessage.addListener(function(msg) { 
    // Save the number of coins in a local variable 
    _playerCoins = msg; 
    // Display number of coins on my browser action html page 
    document.getElementById("coins").innerHTML="Coins: " + _playerCoins; 
}); 

背景スクリプト:

// Add a listener for port connections 
chrome.runtime.onConnect.addListener(function(port) { 
    // If there is a 'getCoins' connection coming in... 
    if(port.name == "getCoins") { 
     // ...add a listener that is called when the other side posts a message on the port. 
     port.onMessage.addListener(function(msg) { 
      port.postMessage(_playerCoins); 
     }); 
    } 
} 
関連する問題