【问题标题】:Message Passing issues in Chrome ExtensionChrome 扩展程序中的消息传递问题
【发布时间】:2012-09-28 11:20:39
【问题描述】:

我正在尝试将消息从我的内容脚本传递到我的后台页面。执行内容脚本时出现此错误:

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 文档中的示例,因此它们应该起作用。

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

【问题讨论】:

  • 无法重现。我确定您没有将该脚本用作内容脚本(可能是注入的<script>?)您能否展示代码的真正重要的结构
  • @RobW 感谢您的努力!我将整个内容脚本编辑到其中。你还需要什么?

标签: javascript google-chrome google-chrome-extension


【解决方案1】:

sendRequestonRequestdeprecated。您需要使用sendMessageonMessage

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

【讨论】:

  • 我调整了我的代码,但它仍然不起作用(同样的错误)。无论如何,谢谢!
【解决方案2】:

问题是您对脚本执行环境的误解造成的。阅读Chrome extension code vs Content scripts vs Injected scripts 了解更多信息。准确地说,您使用this method 的形式在网页上下文中执行代码。网页无权访问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();

* 仅当框架位于同一原点时才有效。否则,您需要this method 才能正确执行代码。

【讨论】:

  • 谢谢,我想我现在明白了一点。无论如何,我现在收到此错误:端口错误:无法建立连接。接收端不存在。
  • @dislick 确保使用onMessage + sendMessage onRequest + sendRequest。尽管这些方法具有相似的签名,但它们是not compatible
  • 哇,这正是我的问题!谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多