Reputation: 129
I am making a extension in Chrome and need to stop a page load (without loading the page completely) and redirect to a url if matches from ajax query.
I am using content_scripts
.
And tried to use
window.location.replace("http://facebook.com");
But the redirect occurs once the page load is completed..
Even tried to use
window.stop();
this is also not working to stop page loading.
Is there any possible way to stop a page load and redirect it before page load?
Upvotes: 2
Views: 5097
Reputation: 77523
You're trying this with a content script.
Content scripts have a run_at
parameter, which indicates when (relative to page loading) they execute.
By default, content scripts run at document_idle
level: Chrome waits until the page has completely loaded before executing it.
You have two options:
You can keep the content script route, but you need to indicate "run_at" : "document_start"
parameter in the content script configuration.
This will execute your code as soon as possible (before the document is loaded, but after the response is started).
If you're concerned about not loading the page at all (not sending a request to the site), you need to intercept it at a lower level. webRequest
API can provide the means to do that.
If you catch the request at onBeforeRequest
event, you can redirect it before it is even sent. Filtering by type is recommended. Note that you won't even need a content script in this case: webRequest
events need to be listened to in a background script.
See the CatBlock example.
Upvotes: 4