Skip to content

Instantly share code, notes, and snippets.

@syoichi
Created July 25, 2012 15:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save syoichi/3176714 to your computer and use it in GitHub Desktop.
Save syoichi/3176714 to your computer and use it in GitHub Desktop.
Manifest Version 2のChrome拡張で、他の拡張のJavaScriptファイルをBackground ScriptからXHRで取得する方法と実行する方法

他の拡張のJavaScriptファイルを取得・実行できると、その拡張がインストールされていて有効になっている事がわかるExtension Messaging APIによる拡張間通信(受信側にEvent Listenerが設定されている場合)や、Management APIによっても知る事は可能。

検証環境はWindows 7 Home Premium SP1 64bit上のChrome 20.0.1132.57、Chromium 22.0.1217.0 (148295)。

XHRで取得する

取得するファイルを持つ拡張で、Manifestのweb_accessible_resourcesにファイルを登録しておく。

"web_accessible_resources": [
    "check.js"
],

これでXHRで取得可能になる。

/*jslint browser: true, devel: true, maxlen: 80*/
// Edition 2012-07-23

(function executeGetOtherExtensionJSByXHR() {
    'use strict';

    var OTHER_EXTENSION_JS, xhr, log;

    OTHER_EXTENSION_JS = 'chrome-extension://<EXTENSION_ID>/check.js';

    xhr = new XMLHttpRequest();

    log = function log(evt) {
        var xhr;

        xhr = evt.target;

        if (/^(?:200|304)$/.test(xhr.status)) {
            console.log(xhr.responseText);

            return;
        }

        console.error('loading error');
    };

    xhr.addEventListener('load', log);
    xhr.addEventListener('error', log);

    xhr.open('GET', OTHER_EXTENSION_JS);
    xhr.responseType = 'text';
    xhr.send(null);
}());

取得したコードは、CSPにより、Data URIによる読み込み、Inline JavaScript、javascriptスキーム、eval、Function、setTimeout、setIntervalによる実行はできないはず(参考)。blobスキームfilesystemスキームについてはわからない。
なお、web_accessible_resourcesに登録するとWeb上から取得も実行もできてしまうので注意が必要。

実行する

実行したい拡張で、Manifestのcontent_security_policyに実行するファイルを持つ拡張のOriginを登録しておく。アプリではcontent_security_policyを変更できないらしい。

"content_security_policy": "script-src 'self' chrome-extension://<EXTENSION_ID>; object-src 'self'",

後はBackground Pageで読みこめば実行できる。

/*jslint browser: true, maxlen: 80*/
// Edition 2012-07-23

(function executeLoadOtherExtensionJS(doc) {
    'use strict';

    var OTHER_EXTENSION_JS;

    OTHER_EXTENSION_JS = 'chrome-extension://<EXTENSION_ID>/check.js';

    doc.head.appendChild(doc.createElement('script')).src = OTHER_EXTENSION_JS;
}(document));

何故これが可能なのかは不明。Relaxing the default policyでは特に言及されてない。不具合かもしれないので、そのうちできなくなるかもしれない。

ちなみに、Manifest Version 1の拡張のJavaScriptファイルは、何も設定しなくても他の拡張から実行する事ができてしまう。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment