我试图根据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.
的chrome.runtime.sendMessage
功能。
我不确定我缺少什么。我们的任何帮助将不胜感激。
您一直试图将带有<script>
标签的内容脚本注入页面。
完成此操作后,您的脚本将不再是内容脚本:它将在页面上下文中执行,并失去对Chrome API的所有提升的访问权限,包括sendMessage
。
要使用jQuery,您不应该依赖页面提供的副本-它在另一个上下文中,因此无法使用。您需要在文件中包含jQuery的本地副本,并在脚本之前加载它:
如果您使用清单来注入脚本,则可以在脚本之前将jQuery添加到列表中:
"content_scripts": [
{
matches: ["http://*.example.com/*"],
js: ["jquery.js", "content.js"]
}
],
如果使用程序注入,请对脚本进行链式加载以确保加载顺序:
chrome.tabs.executeScript(tabId, {file: "jquery.js"}, function() {
chrome.tabs.executeScript(tabId, {file: "content.js"});
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句