我正在尝试将一条消息从我的内容脚本传递到我的背景页面。执行内容脚本时会发生此错误:
Uncaught TypeError: Cannot call method 'sendRequest' of undefined 内容脚本:
function injectFunction(func, exec) {
var script = document.createElement("script");
script.textContent = "-" + func + (exec ? "()" : "");
document.body.appendChild(script);
}
function login() {
chrome.extension.sendMessage({greeting: "hello"}, function(response) {
console.log(response.farewell);
});
var d = window.mainFrame.document;
d.getElementsByName("email")[0].value = "I need the response data here";
d.getElementsByName("passwort")[0].value = "Here too.";
d.forms["login"].submit();
}
injectFunction(login, true);背景:
chrome.extension.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.greeting == "hello")
sendResponse({farewell: "goodbye"});
});manifest.json:
{
"name": "Sephir Auto-Login",
"version": "1.0",
"manifest_version": 2,
"description": "Contact x@x.com for support or further information.",
"options_page": "options.html",
"icons":{
"128":"icon.png"
},
"background": {
"scripts": ["eventPage.js"]
},
"content_scripts": [
{
"matches": ["https://somewebsite/*"],
"js": ["login.js"]
},
{
"matches": ["somewebsite/*"],
"js": ["changePicture.js"]
}
],
"permissions": [
"storage",
"http://*/*",
"https://*/*",
"tabs"
]
}这些都是google文档中的例子,所以它们应该能工作。
有什么帮助吗?我完全迷路了。
发布于 2012-10-08 08:42:23
这个问题是由您对脚本执行环境的误解引起的。有关更多信息,请阅读Chrome扩展代码与内容脚本和注入脚本。准确地说,您正在使用一种形式的这种方法在网页上下文中执行代码。网页没有任何访问chrome.extension API的权限。
我建议重写代码,不要使用注入的脚本,因为在这种情况下没有必要。
function login() {
chrome.extension.sendRequest({greeting: "hello"}, function(response) {
console.log(response.farewell);
});
var d = document.getElementById('mainFrame').contentDocument;
d.getElementsByName("email")[0].value = "I need the response data here";
d.getElementsByName("passwort")[0].value = "Here too.";
d.forms["login"].submit();
}
login();只有当帧位于同一原点时,*才能工作。否则,需要这种方法来正确执行代码。
发布于 2012-10-08 08:38:53
sendRequest和onRequest是已弃用。您需要使用sendMessage和onMessage。
另外,您正在向DOM注入函数,这使得它在内容脚本上下文之外运行,因此chrome.extension API不再适用于该函数。
https://stackoverflow.com/questions/12777810
复制相似问题