How to track page change (Chrome Context Script plugin)?
I'm writing a simple Chrome plugin that's intended to delete DOM elements from some site.
manifest.json
{
"name": "bla",
"version": "1.0",
"description": "bla"开发者_开发问答,
"content_scripts": [
{
"matches": ["http://*/*"],
"js": ["myscript.js"]
}
],
"permissions": [
"tabs",
"http://*/*"
]
}
myscript.js
window.onload = start;
function start()
{
var ads = document.getElementById("left_ads");
ads.parentNode.removeChild(ads);
alert("bla");
}
When I load a target page everything works perfectly: div id="left_ads"
is removed as intended. But, when I click a link to a page which also has a similar div id="left_ads"
my script fails to work. I know that probably I should choose some other event, not window.onload()
, but which one?
It turns out I've found a solution to this. I used background html file. So, the plugin now looks like this:
manifest.json:
{
"name": "bla",
"version": "1.0",
"description": "bla",
"background_page": "background.html",
"permissions": [
"tabs",
"http://*/*"
]
}
background.html:
<html>
<script>
chrome.tabs.onUpdated.addListener(start);
function start(tabID, changeInfo, tab)
{
chrome.tabs.executeScript(null, { file: "myscript.js" })
}
</script>
</html>
myscript.js:
var ads = document.getElementById("left_ads");
ads.parentNode.removeChild(ads);
Works OK, on every page.
精彩评论