首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Chrome扩展中的消息传递问题

Chrome扩展中的消息传递问题
EN

Stack Overflow用户
提问于 2012-10-08 08:22:27
回答 2查看 307关注 0票数 0

我正在尝试将一条消息从我的内容脚本传递到我的背景页面。执行内容脚本时会发生此错误:

代码语言:javascript
复制
Uncaught TypeError: Cannot call method 'sendRequest' of undefined 

内容脚本:

代码语言:javascript
复制
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);

背景:

代码语言:javascript
复制
 chrome.extension.onMessage.addListener(
 function(request, sender, sendResponse) {
      if (request.greeting == "hello")
      sendResponse({farewell: "goodbye"});
 });

manifest.json:

代码语言:javascript
复制
{
    "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文档中的例子,所以它们应该能工作。

有什么帮助吗?我完全迷路了。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-10-08 08:42:23

这个问题是由您对脚本执行环境的误解引起的。有关更多信息,请阅读Chrome扩展代码与内容脚本和注入脚本。准确地说,您正在使用一种形式的这种方法在网页上下文中执行代码。网页没有任何访问chrome.extension API的权限。

我建议重写代码,不要使用注入的脚本,因为在这种情况下没有必要。

代码语言:javascript
复制
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();

只有当帧位于同一原点时,*才能工作。否则,需要这种方法来正确执行代码。

票数 2
EN

Stack Overflow用户

发布于 2012-10-08 08:38:53

sendRequestonRequest已弃用。您需要使用sendMessageonMessage

另外,您正在向DOM注入函数,这使得它在内容脚本上下文之外运行,因此chrome.extension API不再适用于该函数。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12777810

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档