Reputation: 2143
I'm new to Javascript and Chrome extensions, and I'm working on one that triggers a prompt when the user visits a certain webpage, but It's not prompting when the user visits the webpage.
Here's a simplified version that reproduces the problem:
chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) {
var url = tabs[0].url;
if (url === "example.com") {
confirm("You are visiting " + URL);
}
});
What I was hoping this would do is trigger the prompt when the user visits 'Example.com', but I think that I'm misunderstanding how Chrome pulls the URL from the active tab, and maybe how the event is triggered...
Any tips are appreciated.
Upvotes: 1
Views: 1239
Reputation: 77531
In your answer, you quoted this question, and yet you picked a weird answer out of the bunch of answers there.
Instead of detecting a page load yourself, it's best to rely on Chrome's content script mechanism, which will ensure that your script is executed in every tab that loads the requested webpage.
If you know the list of the webpages in advance, you can filter by them in the manifest:
"content_scripts" : [{
"matches": ["*://*.example1.com/*", "*://*.example2.com/"],
"js": ["confirm.js"]
}],
And then have a very simple confirm.js:
confirm("You are visiting " + location.href);
This will be very efficient as Chrome will natively filter the requests for you.
If you don't know the list of the webpages in advance, you can use a content script on every page and filter it in your code:
"content_scripts" : [{
"matches": ["*://*/*"],
"js": ["confirm.js"]
}],
And the confirm.js (skeleton):
chrome.storage.local.get("hostFilterData", function(data){
if( checkUrl(location.host, data.hostFilterData) ) {
confirm("You are visiting " + location.href);
}
});
function checkUrl(location.host, filterData){
/* your logic goes here */
}
You might also want to add "run_at" : "document_start"
if you want your JS to run at the earliest time possible.
If you really want to keep your logic in the background page, you can listen to various events. chrome.tabs.onUpdated
filtered by changeInfo.status == 'complete'
should work in most cases, but may not always be a good idea. It will fire very late if the page has a slow-loading resource, and might fire again if the page uses anchor-based navigation (you probably don't want that). Even if you go this route, there's little sense doing a tab query after that, since the event includes the tab ID of the page that fired it.
There's also chrome.webNavigation
API providing relevant events.
Upvotes: 2
Reputation: 3840
Try changing
if(url === "example.com")
to
if(url === "example.com" || url === "http://example.com" || url === "https://example.com")
Upvotes: 0