[英]XMLHTTPREQUEST chrome extension not working
我无法使用 XMLHTTPREQUEST 从 Chrome 扩展后台脚本发送数据,我已经启动并运行 wampserver,我还尝试了外部链接,例如 google。
它有什么作用 :
用户输入权限定义选项卡,后台脚本等待热键,按下时启动 content_script 并生成一个字符串,将字符串发送回后台脚本,然后后台脚本应接收该字符串并将其发送到 php 文件, php 文件应该打印 hello, 简单试一下看看是哪里出了问题,后面的 php 会有更多的代码。
但它完全不起作用!
更新
我试图打包扩展然后通过拖放运行它,它不会启动 php 脚本。
我试图卸载 chrome,重新启动,然后再次安装,但没有运气。
我还允许--allow-file-access-from-files
更新 2
我在调试模式下收到以下错误:
扩展::发送请求:41:未捕获的类型错误:无法读取未定义的属性“回调”{TypeError:无法读取未定义的属性“回调”
清单文件
{
"manifest_version": 2,
"name": "Extractor",
"version": "1",
"description": "Extract from 144",
"icons": { "16": "logo16.png",
"48": "logo48.png",
"128": "logo128.png" },
"page_action": {
"default_icon": {
"16": "logo16.png",
"48": "logo48.png",
"128": "logo128.png"
},
"default_title": "Extractor"
},
"background": {
"scripts": ["background.js"],
"persistent": true
},
"content_scripts": [
{
"matches" : ["https://www.msn.com/*"],
"js" : ["content_script.js"]
}
],
"permissions": [
"tabs",
"https://www.msn.com/*",
"activeTab",
"http://localhost/*"
],
"commands": {
"toggle-feature": {
"suggested_key": {
"default": "Ctrl+Shift+1",
"windows": "Ctrl+Shift+2"
},
"description": "Extract now"
}
} ,
"web_accessible_resources": ["content_script.js"]
}
背景.js
chrome.commands.onCommand.addListener(function(command) {
if (command === "toggle-feature") {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
for(var i = 0; i<tabs.length;i++) {
chrome.tabs.executeScript(tabs[i].id, {"file": "content_script.js"});
}
});
}
});
chrome.runtime.onMessage.addListener(
function(message, sender, sendResponse) {
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "http://localhost/test/test.php");
xhttp.send(message.url);
});
content_script.js
var url = 'this is just test' ;
chrome.runtime.sendMessage({ 'url' : url });
测试文件
echo "hello";
您只能从chrome扩展名向代码中manifest.json
中定义的URL发出XHR请求,您应该将http://localhost
添加到manifest.json
"permissions": [
"tabs",
"https://www.msn.com/*",
"activeTab",
"*://*/*",
"http://localhost/"
],
此权限"*://*/*",
无效。 您必须指定协议(http或https)
更多信息:
您可能想检查一下您的代码是否存在自Chrome 33以来已被废弃的chrome.extension.sendRequest
。请改用runtime.sendMessage
。
除此之外,“ 简单一次性请求”指出,如果只需要向扩展的另一部分发送一条消息(并有选择地返回响应),则应使用简化的runtime.sendMessage或tabs.sendMessage。
并且,从内容脚本发送请求看起来像这样:
chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
console.log(response.farewell);
});
在接收端,您需要设置runtime.onMessage
事件侦听器以处理消息。
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
if (request.greeting == "hello")
sendResponse({farewell: "goodbye"});
});
此外,据指出:
sendResponse
回调仅在同步使用或事件处理程序返回true表示将异步响应时才有效。 如果没有处理程序返回true或sendResponse
回调被垃圾回收,则sendMessage
函数的回调将被自动调用。
有关如何发送请求和设置事件侦听器的更多信息,您可能需要检查Message Passing 。
XMLHttpRequest
在后台脚本中不起作用,因为后台脚本是一个服务工作者:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.