Chrome Extension to Redirect to URL with Parameter

我的梦境 提交于 2019-12-13 02:09:50

问题


I'm attempting to create a Chrome extension which will add a parameter to the end of a URL if the URL matches a given pattern (*://*.mydomain.com/s/*). Below is the manifest file and background script I have, but I cannot get it working. What am I doing wrong?

manifest.json:

{
  "manifest_version": 2,
  "name": "Search Grid View",
  "version": "0.1",
  "description": "Changes MyDomain.com search to grid view by default",

  "background": {
     "scripts": ["background.js"]
  },

  "permissions": [
    "tabs",
    "webRequest",
    "*://*.mydomain.com/s/*",
    "webRequestBlocking"
  ]

}

background.js:

chrome.webRequest.onBeforeRequest.addListener(
  function(details) {         
    var currentUrl = tabs[0].url;
    var newUrl = currentUrl + "&style=gridview"
    return { redirectUrl: newUrl};
  },
  {
    urls: [
      '*://*.mydomain.com/s/*'
    ],
    types: ['main_frame']
  },
  ['blocking']);

Thanks in advance for any advice!


回答1:


  1. Use debugger - click your extension's background page on chrome://extensions page and switch to the Sources panel.
  2. To obtain the url use onBeforeRequest's callback parameter
  3. Check if the url is already modified.

chrome.webRequest.onBeforeRequest.addListener(
    function(details) {
        return {
            redirectUrl: details.url + 
                (details.url.indexOf("?") == -1 ? "?" : "") +
                (details.url.indexOf("&style=gridview") == -1 ? "&style=gridview" : "")
        };
    },
    {urls: ['*://*.mydomain.com/s/*'], types: ['main_frame']},
    ['blocking']
);


来源:https://stackoverflow.com/questions/31568721/chrome-extension-to-redirect-to-url-with-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!