Reputation: 380
I'm trying to create an extension to automate some tasks. I'm trying to load a page and then execute a code once the page has been loaded but I couldn't find the right way to do this.
custom.js:
var func=function(){
var actualCode = '(' + function() {
//load the new page
window.location='http://page.com/'
} + ')();';
// inserts the code into the current page tab
chrome.tabs.executeScript(null, { code:actualCode})
//--Execute this code once the page is loaded--
}
document.getElementById('btn').addEventListener("click",func);
index.html:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button id="btn"> BTN </button>
<script src="custom.js">
</script>
</body>
</html>
Upvotes: 0
Views: 4621
Reputation: 3702
You can use Content Scripts.
Example from docs: you need to modify manifest.json
to allow extension automatically inject some javascript for websites if urls are matching to the pattern.
{
"name": "My extension",
...
"content_scripts": [
{
"matches": ["http://www.google.com/*"],
"js": ["myscript.js", "myscript2.js"]
}
],
...
}
You can also define run_at
property to control when the files in js are injected. It can be "document_start", "document_end", or "document_idle".
Upvotes: 1
Reputation: 17651
Try using chrome.tabs.onUpdated.addListener to check if the page has been fully loaded where status is equal to 'completed'.
Use the code samples which was given in this SO thread:
chrome.tabs.onUpdated.addListener( function (tabId, changeInfo, tab) {
if (changeInfo.status == 'complete') {
// execute some codes here
}
})
Upvotes: 1
Reputation: 13489
To track the new page and run any logic on it, one solution could be adding this logic inside a content script file that loads at the document_end and every time you navigate to the any page using window.location
, this logic will run.
You may add some conditions to make sure you logic run on the wanted pages/elements.
Am I clear enough?
Upvotes: 1
Reputation: 543
I'm not sure I understood well but this should work if I understood well.
document.addEventListener("DOMContentLoaded",yourFunctionGoesHere)
Upvotes: 0