Reputation: 4212
I'm building a devtool extension and would like to inject my script again when the current page navigates to a different page:
chrome.webNavigation.onDOMContentLoaded.addListener(function(object details) { ... });
I have been on this for several days now but I can't figure out where to place the codes. Im using this template at github: https://github.com/thingsinjars/devtools-extension
I can listen to and inject script and execute scripts from the content script but I can't figure out how to listen for tab url change and inject my code/script into the next page.
Upvotes: 1
Views: 1101
Reputation: 2852
I'm also, writing an extension, and even though I'm also stuck for a couple of days on a communication issue, I think I can help you to understand a little more:
First: the js file associated with the devtools will be tied with the page the devtools is currently inspecting (when I say tied it means that the related to each other, but they don't share the same context or access to google's extension api).
Second: the background page runs on its own sandbox environment and keep one instance per extension, what means that your panel my have multiple instances on different pages, but they all share the same background page.
Now to try to answer your question:
Your panel script (often called devtools.js) should send a message to your background page informing that it should start tracking the navigation of tabs, and your background page should listen for messages from any open panel of your extension and perform the necessary actions ( start tracking navigation of needed tabs and inject script after page loading):
devtools.js
chrome.runtime.sendMessage( {
message: 'track-navigation',
of: chrome.devtools.inspectedWindow.tabId
} );
background.js
var trackedTabs = [];
function injectScript( details ) {
if ( trackedTabs.indexOf( details.tabId ) ) {
chrome.tabs.executeScript( details.tabId, { file: 'include/some-script.js' } );
}
}
function trackNavigation() {
chrome.webNavigation.onDOMContentLoaded.addListener( injectScript, {
// here I've included some filtering in order to restrict urls to listen to
url: [
{ hostContains: 'www.sample.com', ports: [80, 443] },
{ hostContains: 'www.sample.local', ports: [80, 443] }
]
} );
}
chrome.runtime.onMessage.addListener( function( request, sender, sendResponse ) {
switch ( request.message ) {
case 'track-navigation':
trackedTabs.push( request.of );
trackNavigation();
break;
}
} );
While there are other ways of accomplishing the same thing (such as sending a message from the page being tracked where it is about to load, so you don't have to track pages being loaded on the background script); I think this should help you with your question.
Upvotes: 1