Stop page load and redirect in a content script

橙三吉。 提交于 2020-02-07 06:09:50

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/28527149/stop-page-load-and-redirect-in-a-content-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!