我正在开发一个小型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>
window.open("blank.html");
一个新选项卡时,URL是您的扩展名。当您想要进入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讨厌同步,因此您必须使用async请求:
open("GET", url, true);
现在的问题是您实际上并没有进行重定向,而是在google.com上获取了代码并将其写入扩展的本地html页面。因此,将无法访问资源的任何相对路径(例如图像,CSS,JavaScript文件等)。如果您想朝这个方向发展,则必须添加<base>
,(或解析并重写所有相对URL)。
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
。例如:
"matches": [
"http://google.com.au/*",
"https://google.com.au/*",
"http://www.google.com.au/*",
"https://www.google.com.au/*"
],
好的。说完所有这些之后,这可能不是解决问题的最佳方法。但我希望您至少学到了一两件事。
它的核心是:
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句