我正在开发一个小型Chrome扩展程序,当你转到google.com.au时,我不想自动重定向到“redirect.js”,但它无效。如果我手动转到“redirect.js”中显示的“blank.html”文件,我的“httpGet”功能将无效。
{
"name": "Simon Extended",
"description": "Beautify's Simon.",
"version": "1.0",
"manifest_version": 2,
"icons": {
"512": "icon.png"
},
"background": {
"scripts": ["redirect.js"]
},
"browser_action": {
"default_title": "Simon Extended"
},
"content_scripts": [
{
"matches": ["http://google.com.au/*", "https://google.com.au/*"],
"js": ["redirect.js"],
"run_at": "document_start"
}
]
}
function httpGet(theUrl)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
return xmlhttp.responseText;
}
}
xmlhttp.open("GET", theUrl, false );
xmlhttp.send();
}
chrome.browserAction.onClicked.addListener(function(tab) {
window.open("blank.html")
document.write(httpGet("http://google.com"))
});
<html>
<head>
<title>Blank</title>
</head>
<body>
</body>
</html>
答案 0 :(得分:1)
window.open("blank.html");
时,您打开了一个新标签,其中的网址是您的扩展程序。如果您希望write
到该窗口,您必须说出以下内容:
var win = window.open("blank.html");
win.document.write('some HTML');
ncr
添加到路径:
https://www.google.com/ncr 由于XHR请求是跨域的,因此您必须在目标域的manifest.json
文件中添加权限。类似的东西:
"permissions": [
"http://www.google.com/*",
"https://www.google.com/*",
]
由于这是Chrome的扩展程序,因此您知道它有XMLHttpRequest
,因此无需检查。此外,您可以使用onload
代替onreadystatechange
进行检查。
由于WHATWG和Chrome讨厌同步的任何内容,您必须use async request:
open("GET", url, true);
现在您的问题变成了您实际上没有进行重定向,而是在 google.com 中提取代码并将其写入本地 html页面为您的扩展。因此,任何与资源相关的路径(例如图像,CSS,JavaScript文件等)都无法访问。如果您想要朝这个方向前进,则必须添加<base>
,(或解析并重写所有相关网址)。
您的最终redirect.js
可能类似于:
function http_set(url, win)
{
var xhr = new XMLHttpRequest();
xhr.onload = function() {
var html = xhr.responseText.replace('<head>', '<head><base href="'+url+'">');
win.document.write(html);
win.document.close();
}
xhr.open("GET", url, true);
xhr.send();
}
chrome.browserAction.onClicked.addListener(function(tab) {
var win = window.open("blank.html");
http_set("https://www.google.com/ncr", win);
});
因此,不是加载来自google.com的HTML代码,您可以这样说:
chrome.browserAction.onClicked.addListener(function(tab) {
window.open("https://www.google.com/ncr");
});
现在。这样做的结果是,当您点击扩展程序的图标时,会打开一个带有google.com的新标签页。
对于您请求的效果,您可以使用此redirect.js
文件:
window.location = "https://www.google.com/ncr";
是的,那是整个文件。有了这个,您可以删除我们在清单文件中添加的权限,只添加触发域。
为此:您还需要匹配www
。 E.g:
"matches": [
"http://google.com.au/*",
"https://google.com.au/*",
"http://www.google.com.au/*",
"https://www.google.com.au/*"
],
行。完成所有这些之后,可能不是解决问题的最佳方法。但我希望你至少学过一两件事。
它的核心是: