Is it possible to rewrite a URL (with additional parameters) with the Chrome extension

I am trying to add a few additional parameters to the URL that the user entered (before the page loads). Can this be done?

For example, if the custom types are www.google.com , I would like to add ?q=query in the url (final: www.google.com?q=query .

thanks

+8
google-chrome-extension
source share
2 answers

The webRequest API may be what you need. This code is on 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/ using http://www.google.com/?q=defaultquery , but I think you can see how to expand it to add more functionality.

Please note that this redirects all attempts to reach http://www.google.com/ , including Ajax and iframes requests.

In the documentation, you will need to add the webRequest and webRequestBlocking , as well as the host permissions for each host that you plan to intercept:

 "permissions": [ "webRequest", "webRequestBlocking", "*://*.google.com/", ... ], 
+8
source share

This is an old question, but I am responsible for it for future readers.

Modifying request parameters is a bit complicated because you can end an infinite loop, and chrome / firefox can detect it and handle any current Url request state.

I ran into this situation in my chrome Requestly extension , where users used the Replace Rule and replaced www.google.com with www.google.com?q=query or did something similar.

The problem with this approach is that the browser can intercept the request URL after adding the request parameter, so that the parameter is added several times and distorts the URL. Therefore, you must provide one of the following: -

  • Do not intercept the request after redirecting it.
  • Check if the parameter exists, do not redirect it.

As @apsillers correctly pointed out in his answer, you should use the webRequest API to make any changes to the URL. Look at his answer and write your code accordingly.

Just in case you are looking for an already available solution, try the Order Request Rule . Here is a screenshot of how it looks: -

enter image description here

For Firefox, you can download Requestly from your home page.

+1
source share

All Articles