[英]Chrome Extension not running scripts on document start and not printing content
我正在开发一个小型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/*"
],
好。 说完所有这些之后,这可能不是解决问题的最佳方法。 但我希望您至少学到了一两件事。
它的核心是:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.