Chrome扩展程序会修改建议和搜索网址

时间:2016-08-25 13:49:31

标签: javascript google-chrome search google-chrome-extension

我有此扩展程序可更改用户的默认搜索提供程序:

"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_urlsuggest_url已修复且正在运行。

但是,安装我的扩展程序并首次运行background.js后,系统会生成uid并将其存储在localStorage中。我需要将此uidsearch_urlsuggest_url一起发送,如果search_url如上所示:

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

我需要它是这样的:

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

当用户在网址栏中搜索某些内容时,如何传递该额外参数?

1 个答案:

答案 0 :(得分:1)

这样的事情可以在后台页面中使用webRequest API

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"]
  );
}

需要"webRequest""webRequestBlocking"权限以及持久性背景页面(无法使用"persistent": false)。