【问题标题】:Chrome Extension to Redirect to URL with Parameter使用参数重定向到 URL 的 Chrome 扩展
【发布时间】:2015-10-12 15:48:05
【问题描述】:

我正在尝试创建一个 Chrome 扩展程序,如果 URL 与给定模式 (*://*.mydomain.com/s/*) 匹配,它将在 URL 末尾添加一个参数。下面是我拥有的清单文件和后台脚本,但我无法让它工作。我做错了什么?

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']);

提前感谢您的任何建议!

【问题讨论】:

  • browserAction 表示地址栏中的图标(多功能框),请参阅the API docs。否则你需要一个后台脚本和webRequestwebNavigation API。请澄清问题。
  • 尝试“lastFocusedWindow: true”而不是“currentWindow: true”
  • @wOxxOm 谢谢! Chrome 扩展程序非常新,所以我一直在尝试将不同的示例组合在一起,但显然效果不佳。我已经更新了上面的问题并重写了结构以使用带有 webRequest API 的背景页面。话虽如此,它仍然无法正常工作。知道有什么问题吗?
  • 尝试使用this question 中的代码替换相应的值。因此,您将在 将其发送到服务器之前修改 url,从而消除页面刷新闪烁。
  • @wOxxOm 我更新了我的 background.js 代码,但仍然没有任何反应。看看上面更新的代码。我还在 manifest.json 中添加了 webRequestBlocking 权限,因为我很确定现在这是必要的。还有什么想法吗?

标签: javascript google-chrome google-chrome-extension content-script


【解决方案1】:
  1. 使用调试器 - 在 chrome://extensions 页面上单击您的扩展程序的 background page 并切换到 Sources 面板。
  2. 获取url使用onBeforeRequest的回调参数
  3. 检查url是否已经修改。

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']
);

【讨论】:

  • 谢谢!您提供的更新代码完美运行。不幸的是,我又遇到了一个问题......现在我意识到有时 URL 已经有一个参数,有时它没有。所以,我需要检查是否有“?”在网址中。如果有,我需要附加“&style=gridview”,否则我需要附加“?style=gridview”。解决这个问题的最佳方法是什么?再次感谢您的帮助!
  • 有很多方法可以实现,例如使用indexOf,查看更新后的代码。
猜你喜欢
  • 2014-08-17
  • 2012-08-17
  • 2017-01-25
  • 2014-11-04
  • 2020-08-25
  • 2012-03-17
  • 2021-03-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多