chrome拡張機能のcontent_scriptから簡単なJSを再実行するのが難しいです。基本的には私がセットアップしたものです。次のコードは動作しますが、一度だけ:DOMを変更してクロム拡張用のコンテンツスクリプトを更新する方法
manifest.jsonを
{
"content_scripts": [ {
"matches": ["https://www.amazon.com/*"],
"js": ["./content_scraper.js", "./main.js"],
"run_at": "document_end"
} ],
"permissions": ["tabs","webNavigation"]
}
content_scraper.js
function dataUpdater() {
// this function scrapes the page and updates the data var
}
chrome.runtime.onMessage.addListener(
function(message, sender, sendResponse) {
switch(message.type) {
case "getItems":
sendResponse(data)
break;
}
}
);
main.js
function getItemsData() {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {type: "getItems"}, function(resp) {
resp.map(item => {
// do some things
}
})
})
}
document.addEventListener("DOMContentLoaded", getItemsData)
したがって、上記のコードはDOMContentが読み込まれた後に動作します。私はDOMNodeInsertedイベントを試して、document.readyState
を読んで再度スクリプトを起動しましたが、content_scriptsからdataUpdater関数にアクセスできないようです。
私は、DOMが更新されるたびにcontent_scraper.js(content_scriptsにある)を実行しようとしています。助けてくれてありがとう!