1
0

More than 3 years have passed since last update.

動的に読み込んだJavaScript内でchrome.extension.getURLを使う方法

Last updated at Posted at 2020-01-06

問題点

Chrome拡張機能で拡張機能のアイコンをクリックしたときに必要なjsを読み込んだら、読み込まれた方のjsの中ではchrome.extension.getURLを使えなかった。

間違ったコード

entry.js
appendScript("main.js");
function appendScript(url) {
    chrome.extension.getURL(url);
    const el = document.createElement('script');
    el.src = url;
    document.body.appendChild(el);
};
main.js
chrome.extension.getURL("resource.jpg"); //TypeError: Cannot read property 'getURL' of undefined

正しいコード

appendChildの代わりにevalでそのまま読み込む。

entry.js
appendScript("main.js");
function appendScript(url) {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', chrome.extension.getURL(url), true);
    xhr.onload = e => {
        if (xhr.status === 200)
            eval(xhr.responseText);
    };
    xhr.send();
};
};

(2020/3/1追記)
あるいはpopupまたはbackgroudの中ではJavaScriptもCSSも読み込む用のAPIが用意されているので
sendMessaageと組み合わせればページ内に読み込むこともできそうです。

popup.js(一部)
    chrome.tabs.executeScript(null, { file: "main.js" });
    chrome.tabs.insertCSS(null, { file: "main.css" });
};

参考

こちらの内容をまとめて記事にしました。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0