【问题标题】:Redirecting on page load with a Chrome extension使用 Chrome 扩展程序在页面加载时重定向
【发布时间】:2014-06-04 11:53:37
【问题描述】:

我正在开发一个 Chrome 扩展程序,它可以自动将非 HTTPS 站点的用户重定向到 HTTPS 版本。

但是,当前的问题是用户必须手动激活此重定向。

使用 manifest.json 中的 content_scripts 很容易实现,但是,根据 Chrome 文档,内容脚本“不能...使用 chrome.* API(chrome.extension 的部分除外)”。

所以,这是我的扩展的清单文件:

{
  "name": "SSL Redirect",
  "version": "1.0",
  "manifest_version": 2,
  "description": "Redirects plain HTTP domain.com to the encrypted, HTTPS secured version.",

  "permissions": [ "tabs", "http://*/*", "https://*/*" ],

  "background" : {
  "page": "body.html"
  },

"browser_action": {
          "default_icon": "icon.png"
},
  "content_scripts": [
    {
      "matches": ["http://www.domain.com/*"],
      "js": ["redirect.js"]
    }
  ]
}

这是 js:

var domain = /domain.com\//;
var ssldomain = "ssl.domain.com\/";

function updateUrl(tab){

  if(tab.url.match(ssldomain)) {
    alert("You're already using the SSL site. :)")
    throw { name: 'Error', message: 'Stopped running, already in SSL mode.' };
  }

  if(tab.url.match(domain)) {
    var newurl = tab.url.replace(domain, ssldomain);
    newurl = newurl.replace(/^http:/, 'https:');
    newurl = newurl.replace("www.", "");
    chrome.tabs.update(tab.id, {url: newurl});
  }

  if(!(tab.url.match(domain))) {
    alert("This extension only works on domain.com.")
    throw { name: 'Error', message: 'Stopped running, not on domain.com.' };
  }


  }

chrome.browserAction.onClicked.addListener(function(tab) {updateUrl(tab);});

我的最终目标是让它在任何匹配 domain.com 的页面上自动运行,无需用户交互。

我有点卡住了。有什么想法吗?

【问题讨论】:

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


    【解决方案1】:

    1) 在内容脚本中,您可以使用标准方法更改 URL,因为您是在页面上下文中运行的。即:

    var oldUrl = location.href;
    /* construct newUrl */
    if(newUrl != oldUrl) location.replace(newUrl);
    

    2) 废弃你已经写过的内容并阅读有关chrome.webRequest API 的内容。 这将实现您所需要的,无需内容脚本或选项卡操作。

    例子:

     chrome.webRequest.onBeforeRequest.addListener(
       function(details) {
         var url = details.url.replace(/^http/, "https");
         return {redirectUrl: url};
       },
       {urls: ["http://domain.com/*"]},
       ["blocking"]
     );
    

    注意:您需要"*://domain.com/*"的主机权限

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-22
      • 1970-01-01
      • 2012-03-17
      相关资源
      最近更新 更多