clzola clzola - 3 months ago 23
Javascript Question

Chrome extension modify suggest and search urls

I have this extension that changes user's default search provider:

"chrome_settings_overrides" : {
"homepage" : "http://example.com/",

"search_provider" : {
"name": "Example Search",
"is_default" : true,
"encoding" : "UTF-8",
"favicon_url": "http://example.com/favicon.png",
"keyword" : "obifind",
"search_url" : "http://example.com/?q={searchTerms}&gid=DWB020344",
"suggest_url" : "http://example.com/suggest.php?q={searchTerms}&gid=DWB020344"
},
"startup_pages" : ["http://example.com"]
},


search_url
and
suggest_url
are fixed and they are working.

However, when my extension is installed and
background.js
is runned for the first time, an
uid
is generated and stored in
localStorage
. I need for this
uid
to also be sent in query with
search_url
and
suggest_url
like if
search_url
is like one above:

http://example.com/?q={searchTerms}&gid=DWB020344


i need it to be like this:

http://example.com/?q={searchTerms}&gid=DWB020344&uid=00445c2e-6aca-11e6-8b77-86f30ca893d3
.

How do I pass that extra parameter when user searches something in url bar?

Xan Xan
Answer

Something like that should do the trick, using webRequest API in the background page:

var uid = localStorage["uid"]; // Have it ready for max performance of webRequest

if (navigator.doNotTrack != 1) { // Let's not be evil, OK?
  chrome.webRequest.onBeforeRequest.addListener(
    function(details) {
      if (details.url.indexOf("uid=") == -1) { // If no UID yet
        return { // return a BlockingResponse object
          redirectUrl: request.url.replace("?", "?uid=" + uid + "&")
          // Add uid as first parameter, to make sure we don't run into URL fragments
        };
      }
    },
    {urls: ["http://example.com/?*gid=DWB020344*"]},
    ["blocking"]
  );
}

Requires "webRequest" and "webRequestBlocking" permissions and a persistent background page (can't use "persistent": false).

Comments