在我的后台脚本中,我按如下方式注入了我的contentScript:
function reqHandler()
{
alert("hello");
var imgData = "" + this.responseText;
//document.write("" + imgData);
document.body.innerHTML = "";
var img = document.createElement("img");
img.setAttribute("src", 'data:image/jpeg;base64,' + "" + imgData);
document.body.appendChild(img);
}
//debugger;
var PDFdata = document.body.innerHTML;
document.body.innerHTML = "";
var xhr = new XMLHttpRequest();
xhr.onload = reqHandler;
xhr.open("GET", "http://localhost:81/getImage.php", true);
xhr.send();
在reqHandler
我有以下代码:
{
"manifest_version": 2,
"name": "My Extension",
"version": "1.0",
"background": {
"scripts": ["background.js"],
"persistent": true
},
"permissions": [
"webRequest",
"<all_urls>",
"webRequestBlocking",
"tabs",
"webNavigation"
]
}
正如您所看到的,我在这里制作了跨源的XMLHTTPRequest。我面临的问题是正在执行content.js脚本,但我的{{1}}函数应该在xhr请求完成后运行。
其中的警报未显示。可能是什么问题?
更新 这是扩展名的清单文件:
{{1}}
答案 0 :(得分:1)
AFAIK仅在特权上下文中执行的内部扩展脚本(如后台页面脚本(不是无法访问特权API的内容脚本))可以生成跨域XMLHttpRequest(更多信息在{{3 }})。
在后台页面脚本中调用XHR,official docs到标签的内容脚本。
background.js:
chrome.webRequest.onHeadersReceived.addListener(function(details){
if(isPDF(details))
{
var xhr = new XMLHttpRequest();
var tabId = details.tabId; // save id in the local context
xhr.onload = function() {
chrome.tabs.sendMessage(tabId, {imgData: this.responseText});
};
xhr.open("GET", "http://localhost:81/getImage.php", true);
xhr.send();
chrome.tabs.executeScript(details.tabId, {file: "content.js", ..............
..................
内容脚本:
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
if (message.imgData) {
document.body.innerHTML = "";
var img = document.createElement("img");
img.src = "data:image/jpeg;base64," + message.imgData;
document.body.appendChild(img);
}
});