コンテンツ スクリプトまたは挿入されたスクリプトからバックグラウンド ページのグローバル オブジェクトに直接アクセスする方法はありません。
挿入されたスクリプトからバックグラウンド ページのメソッドを使用するには、次の手順に従います。
- コンテンツ スクリプト: イベント リスナーをページの例 1にバインドします。
バックグラウンドページからメソッドに通知したいときはいつでも:
- 注入されたスクリプト: この特定のイベント例 1を作成して起動します。
→ 1)
のイベントリスナーがトリガーされます。
- このイベント リスナーでは、バックグラウンドの例 2
chrome.runtime.sendMessage
の機能を要求するために使用します。
- バックグラウンド ページで、 を使用してこのリクエストを処理し
chrome.runtime.onMessage
ます。
- 必要に応じて、 を使用して元のタブにコードを挿入します
chrome.tabs.executeScript(tab.id, func)
。
コンテンツ スクリプトから背景ページのメソッドを使用するには、手順 3 と 4 のみが必要です。
コンテンツ スクリプトがバックグラウンド ページと通信する例を次に示します。
// Example background page
function some_method(arg_name) {
return localStorage.getItem(arg_name);
}
chrome.runtime.onMessage.addListener(function(request, sender, callback) {
if (request.type == 'localStorage - step 4') {
callback( some_method(request.name) );
} else if (request.type == 'localStorage - step 5') {
localStorage.setItem(request.name, request.value);
}
});
// Example contentscript.js
chrome.runtime.sendMessage({
type: 'localStorage - step 4',
name: 'preference'
}, function(value) {
if (value === null) {
// Example: If no preference is set, set one:
chrome.runtime.sendMessage({
type: 'localStorage - step 5',
name: 'preference',
value: 'default'
});
}
});
こちらもご覧ください