Gok*_*N K 3 javascript jquery google-chrome google-chrome-extension
我试图根据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);
Run Code Online (Sandbox Code Playgroud)
在我的main.js我做
chrome.runtime.sendMessage({
method: 'GET',
action: 'xhttp',
url: myurl
}, function(responseText) {
console.log("Response Text is ", responseText);
});
Run Code Online (Sandbox Code Playgroud)
在我,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
}
});
Run Code Online (Sandbox Code Playgroud)
我现在面临的问题是我不断收到错误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"]
}
],
Run Code Online (Sandbox Code Playgroud)如果您使用的是编程注入,请对脚本进行链式加载以确保加载顺序:
chrome.tabs.executeScript(tabId, {file: "jquery.js"}, function() {
chrome.tabs.executeScript(tabId, {file: "content.js"});
});
Run Code Online (Sandbox Code Playgroud)| 归档时间: |
|
| 查看次数: |
3067 次 |
| 最近记录: |