0

現在、Chrome 拡張機能を作成しています。しかし、Google は拡張機能が Web ページで定義された変数や関数にアクセスすることを公式に禁止しています。

ただし、コンテンツ スクリプトにはいくつかの制限があります。彼らがすることはできません:

Use chrome.* APIs (except for parts of chrome.extension)
Use variables or functions defined by their extension's pages
Use variables or functions defined by web pages or by other content scripts

アップデート:

このページには、次のような多数のスクリプト タグがあります。

 <script>...<script>
 <script>...<script>
 <script>...<script> 
 <script>
 $config = {};
 $config.a = 1;
 $config.b = 5; 
 function getConfig() {  ...
   // some code  return config; 
 }
 </script> 
 <script>...<script>
 <script>...<script>

コンテンツ スクリプトから $config と関数 getConfig() を読み取る方法はありますか? それともこれは単に不可能ですか?

ありがとう!

4

1 に答える 1

2

お気づきかもしれませんが、chrome.* API は、背景ページまたは他のプラグイン固有のページでのみ使用できます。一方、コンテンツ スクリプトはページにアクセスできますが、chrome.* API は使用できません。

あなたがする必要があるのは、コンテンツ拡張機能を使用してページ上の必要なものにアクセスし、データを含むメッセージをバックグラウンド ページに送り返すことです。バックグラウンド ページは、データと chrome.* API を使用できます。

ドキュメントには、コンテンツ スクリプトとバックグラウンド ページ間のメッセージ パッシングに関する非常に優れた例とドキュメントがあります。

http://developer.chrome.com/extensions/messaging.html

アップデート

JSON オブジェクトを含むメッセージのみを送信できます。つまり、getConfig 関数を送信することはできません。ただし、例では $config を送信できます。$config オブジェクトが JSON でない場合は、何らかの方法でシリアル化する必要があります。

制御できないページ上のコード

$config = {};
$config.a = 1;
$config.b = 5;

contentscript.js

function getConfig(){return $config;}

chrome.extension.sendMessage({type: 'config', content: getConfig()}, function(response) {
  console.log(response.status);
});

background.js

chrome.extension.onMessage.addListener(
  function(request, sender, sendResponse) {
    console.log(sender.tab ?
                "from a content script:" + sender.tab.url :
                "from the extension");
    if (request.type == "config") {
        // DO SOMETHING WITH request.config here
        sendResponse({status: "OK"});
    }
    sendResponse({status: "Unknown request type"});
  });
于 2012-10-22T23:36:43.100 に答える