我正在尝试根据 xhr 调用的输出更改页面的内容。我从 content.js 发送一条消息,在后台 js 文件中进行 xrh 调用,然后将输出传递给 content.js,这会更改页面的内容。
From my content.js
文件我正在执行以下操作。
var s = document.createElement('script');
s.src = chrome.extension.getURL('src/content/main.js');
(document.head || document.documentElement).appendChild(s);
In my main.js
我在做
chrome.runtime.sendMessage({
method: 'GET',
action: 'xhttp',
url: myurl
}, function(responseText) {
console.log("Response Text is ", responseText);
});
而在我的bg.js
我有以下内容
chrome.runtime.onMessage.addListener(function(request, sender, callback) {
if (request.action == "xhttp") {
var xhttp = new XMLHttpRequest();
var method = request.method ? request.method.toUpperCase() : 'GET';
xhttp.onload = function() {
callback(xhttp.responseText);
};
xhttp.onerror = function() {
// Do whatever you want on error. Don't forget to invoke the
// callback to clean up the communication port.
callback('Error');
};
xhttp.open(method, request.url, true);
if (method == 'POST') {
xhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
xhttp.send(request.data);
return true; // prevents the callback from being called too early on return
}
});
我面临的问题是我不断收到错误Invalid arguments to connect.
for chrome.runtime.sendMessage
功能。
我不确定我错过了什么。非常感谢任何帮助我们。