問題点
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" });
};
参考
こちらの内容をまとめて記事にしました。