I have a basic content script in my manifest.json file where I have it match a certain URL and also load up the scripts.
"content_scripts": [
{
"matches": ["http://www.urlhere.com/videos/*"],
"js": ["scripts/jquery-2.1.1.min.js", "scripts/csScript.js"]
}
],
The csScript.js gets an attribute on the page and sends it back to the background.js script through a message.
chrome.runtime.sendMessage({url: getUrl()});
function getUrl() {
url = $('meta[itemprop=contentURL]').attr('content');
return url;
}
The background.js page gets the message with the attribute value, manipulates it, and then shows the page_action icon.
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
url = manipulateUrl(request.url);
chrome.pageAction.show(sender.tab.id);
});
chrome.pageAction.onClicked.addListener(function(tab) {
console.log("url: " + url);
});
This all works fine and dandy on the first page load - the content script gets executed and the message is passed. However, the page has links that goes to other video...when I click on one of those, I notice that the Chrome spinner loads up a new URL in the address bar but the content script is not executed again.
When I click my page_action icon I get the old URL that was passed which indicates that the content script didn't go get the new one for the page.
Any ideas?
The URL is probably changed through history manipulation or URL fragment change, but does not actually reload the page.
If it's a URL fragment change, you can use window.onhashchange event.
If the URL changes completely but page does not reload, it probably is achieved with history.pushState or history.replaceState functions. Unfortunately, they do not trigger any event. It is, therefore, tricky to detect.
A hacky solution would be to inject code into the page to replace history.pushState function in the page's context, so that it also does something you can detect from the content script. It can be a DOM change, a custom event, or a window.postMessage call.
Edit: from a linked question, a better solution is to listen to chrome.webNavigation.onHistoryStateUpdated (credit to joshft91)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With