2017-03-08 7 views
0

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にある)を実行しようとしています。助けてくれてありがとう!

答えて

0

あなたはこのように、MutationObserverを探し、文書本体のsubtreeに観察する必要があります:https://developer.mozilla.org/cs/docs/Web/API/MutationObserver

const observer = new MutationObserver(function(mutations) { 
... 
}); 
observer.observe(document.body, { subtree: true }); 

は、リファレンスを参照してください。

関連する問題