且构网

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

是否可以使用Chrome扩展程序重写网址(使用额外的参数)

更新时间:2023-11-27 14:21:40

webRequest API可能就是你需要的,这段代码放在你的后台页面:

  chrome.webRequest.onBeforeRequest.addListener(
函数(详情){
if(details.url ==http://www.google.com/ )
return {redirectUrl:http://www.google.com/?q=defaultquery};
},
{url:[http://www.google .com / *]},
[blocking]);

这是一个非常具体的规则,通过 http://www.google.com/?q将访问重定向到 http://www.google.com/ = defaultquery ,但我认为你可以看到如何将其扩展到incl ude更多功能。



请注意,这将重新路由所有尝试达到 http://www.google.com / code>,包括Ajax请求和iframe。



根据文档,您需要添加 webRequest webRequestBlocking 权限,以及您计划拦截的每个主机的主机权限:

 permissions:[
webRequest,
webRequestBlocking,
*://*.google.com/,
。 ..
],


I am trying to append few extra parameters to the url that user typed (before the page gets loaded). Is it possible to do?

For example, if user types www.google.com, I would like to append ?q=query to url (final: www.google.com?q=query.

Thanks

The webRequest API might be what you need. This code goes in your background page:

chrome.webRequest.onBeforeRequest.addListener(
    function(details) {
        if( details.url == "http://www.google.com/" )
            return {redirectUrl: "http://www.google.com/?q=defaultquery" };
    },
    {urls: ["http://www.google.com/*"]},
    ["blocking"]);

This is an extremely specific rule that redirects visits to http://www.google.com/ with http://www.google.com/?q=defaultquery, but I think you can see how to expand it to include more functionality.

Note that this will reroute all attempts to reach http://www.google.com/, including Ajax requests and iframes.

Per the documentation, you will need to add the webRequest and webRequestBlocking permissions, along with host permissions for every host you plan to intercept:

"permissions": [
    "webRequest",
    "webRequestBlocking",
    "*://*.google.com/",
    ...
],