【发布时间】:2015-04-13 08:01:55
【问题描述】:
我正在尝试根据 xhr 调用的输出更改页面的内容。我正在从 content.js 发送一条消息,在后台 js 文件中进行 xrh 调用,然后将输出传递给 content.js,这会改变页面的内容。
从我的content.js 文件中,我正在执行以下操作。
var s = document.createElement('script');
s.src = chrome.extension.getURL('src/content/main.js');
(document.head || document.documentElement).appendChild(s);
在我的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 函数的错误。
我不确定我错过了什么。非常感谢我们的任何帮助。
【问题讨论】:
-
如何注入
content.js代码?我没有看到您的代码立即出现任何错误,而且我从未见过这样的错误 - 听起来像是使用connect而不是sendMessage。 -
@Xan 我在 content.js 中使用了以下内容,并且在 main.js 中有剩余的逻辑,因为我希望在执行脚本之前加载 jQuery。看起来这是导致问题的原因。现在我把它移到 content.js 它工作正常。
var s = document.createElement('script'); s.src = chrome.extension.getURL('src/content/main.js'); (document.head || document.documentElement).appendChild(s);但是我现在不能使用 jQuery。有什么解决办法吗? -
啊哈,所以我的理论是正确的。
-
@Xan 感谢您指出这一点。任何想法,为什么这不起作用?将其发布为答案,以便我接受。你也知道如何解决 jQuery 未加载的问题吗?
-
我会的。您可以将此信息编辑到问题本身中吗?
标签: javascript jquery google-chrome google-chrome-extension