Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/google-chrome/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用Chrome扩展在页面加载时重定向_Javascript_Google Chrome_Google Chrome Extension - Fatal编程技术网

Javascript 使用Chrome扩展在页面加载时重定向

Javascript 使用Chrome扩展在页面加载时重定向,javascript,google-chrome,google-chrome-extension,Javascript,Google Chrome,Google Chrome Extension,我正在开发一个Chrome扩展,它可以将非HTTPS站点的用户自动重定向到HTTPS版本 但是,当前的问题是,用户必须手动激活此重定向 使用manifest.json中的content_脚本很容易做到这一点,但是,根据Chrome文档,content脚本“不能…使用Chrome.*api(Chrome.extension的部分除外)” 这是我的扩展名的清单文件: { "name": "SSL Redirect", "version": "1.0", "manifest_version

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

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

使用manifest.json中的content_脚本很容易做到这一点,但是,根据Chrome文档,content脚本“不能…使用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匹配的任何页面上自动运行,而无需用户交互

我有点困了。有什么想法吗?

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

var oldUrl = location.href;
/* construct newUrl */
if(newUrl != oldUrl) location.replace(newUrl);
2) 扔掉你已经写过的东西,读一读。 这将实现您所需要的,而无需内容脚本或选项卡操作

例如:

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