且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

停止页面加载并在内容脚本中重定向

更新时间:2023-09-26 12:19:52

这与内容脚本。



内容脚本有一个 run_at 参数,它表明它们执行的时间(相对于页面加载)。

通过默认情况下,内容脚本在 document_idle 级别运行:Chrome会等到页面完成加载才执行。



您有两种选择:你可以保留内容脚本的路由,但你需要指出run_at :document_start参数在内容脚本配置中。



这将尽快执行您的代码(在文档加载之前,但在respo之后nse开始)。 如果你担心没有加载网页(不向网站发送请求),你需要拦截它在较低的水平。 webRequest API 可以提供实现的途径

如果您在 onBeforeRequest 事件中捕获请求,则可以在发送之前将其重定向。建议按类型过滤。请注意,在这种情况下,甚至不需要内容脚本: webRequest 事件需要在后台脚本中收听。



请参阅 CatBlock示例



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?

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.