Chrome扩展程序sendResponse无效

时间:2017-05-01 18:08:39

标签: google-chrome google-chrome-extension

这个问题有很多版本,我已经对它们进行了审查,并尽我所能尝试了许多事情而没有成功。我是chrome扩展的新手,我可能会遗漏很多东西,但我不知道是什么。

首先,我想指出,我已从各种答案中复制了几个声明的工作示例,但这些都不适用于我。我在Windows 7 Professional上使用Chrome版本58.0.3029.81。

无论是我的代码还是我复制的示例,内容脚本中的代码都会执行,并使用正确的响应调用sendResponse。除此之外,什么都没有 - 指定的回调函数永远不会被执行。

这是我目前的代码:

的manifest.json

{
  "manifest_version": 2,

  "name": "TestExtension",
  "description": "...",
  "version": "1.0",

  "content_scripts": [
    {
      "matches": [
        "http://*/*",
        "https://*/*"
      ],
      "js": [ "content.js" ]
    }
  ],

  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html",
    "default_title": "Send a checkpoint request"
  },

  "permissions": [
    "activeTab",
    "tabs",
    "http://*/*",    // allow any host
    "https://*/*"    // allow any secure host
  ]
}

popup.js

document.addEventListener('DOMContentLoaded', function ()
{

    document.getElementById('extension_form').onsubmit = function ()
    {
        var elementName = "DataAccessURL";

        chrome.tabs.query(
        {
            active: true,
            currentWindow: true
        },
        function (tabs)
        {
            chrome.tabs.sendMessage(
                tabs[0].id,
                { Method: "GetElement", data: elementName },
                function (response)
                {
                    debugger;
                    console.log("response:Element = " + response.Element);
                    alert(response.Element);
                });
        });



    };
});

content.js

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse)
{
    console.log("In Listener");

    if (request.Method && request.Method == "GetElement")
    {
        var result = "";

        var element = request.data;

        console.log(element);

        var e = document.getElementById(element);

        if (e) result = e.innerHTML;

        console.log(result);

        sendResponse({ Element: result });

        return true;    // <-- the presence or absence of this line makes no difference
    }

});

任何线索都会受到赞赏。我根本不明白为什么我的回调没有被调用。

1 个答案:

答案 0 :(得分:0)

用户wOxxOm在他的评论中提供了这个答案。

在popup.js示例中,我附加到'onsubmit'事件表单以触发我的代码。

我之前已经读过,如果弹出窗口关闭,它的代码将不再存在。在我的情况下,我无法直观地告诉我,正如wOxxOm指出的那样,提交事件会重新加载弹出窗口。这就是断开我的代码。

为了防止弹出重新加载,我需要阻止对提交事件的默认操作。我添加了一个'evt'参数来接受submit的event参数,并调用preventDefault,如下所示。

document.getElementById('extension_form').onsubmit = function (evt)
{
    evt.preventDefault();
    ...

这样可以使样本按预期工作。

谢谢wOxxOm!

相关问题