javascript - Chrome 插件消息传递回调未定义

标签 javascript jquery google-chrome-extension callback

我设法在两个文件/实例之间传递消息,即我的弹出窗口和我的后台脚本,但回调函数仍然返回未定义,所以我的弹出脚本没有收到回复。有人可以帮助我吗?我的代码基于 the docs from Google .

Background.js

chrome.runtime.onMessage.addListener(function (sender, sendResponse) {
    var resp = {'navURL': "Not set yet"};
    if (sender.greeting === "GetURL") {
      sendResponse(resp);
    }

  });

popup.js

function getURL() {
  chrome.runtime.sendMessage({
      greeting: "GetURL"
    },
    function (response) {

      // RESPONSE IS UNDEFINED //

      console.log(response);
      alert(response.navURL);
    });
}

$("input[type='checkbox']").on('change', function () {
    getURL();
});

list .json

    {

      "name": "FaceBlock",
      "description": "This extention gets rid of unwanted content on Facebook like sponsored posts, adds or annoying suggestions. The content you wish to see is enlarged for a better and richer social experience.",
      "version": "0.0.1",
      "manifest_version": 2,
      "content_scripts": [
        {
          "matches": [
        "http://*.facebook.com/*", "https://*.facebook.com/*"],
          "css": ["css/popup.css"],
          "js": ["js/jquery.min.js", "js/content.js"],
          "run_at": "document_end",
          "all_frames": true
    }],
      "options_page": "options.html",
    "browser_action": {
        "default_icon": "icon.png",
        "default_popup": "popup.html",
        "default_title": "Faceblock"
    },
      "permissions": [
    "activeTab",
    "tabs",
    "https://www.facebook.com/*",
    "https://ajax.googleapis.com/",
    "storage"
  ],
      "background": {
        "scripts": ["js/background.js"],
        "persistent": false
      },
      "options_ui": {
        // Required.
        "page": "popup.html",
        // Recommended.
        "chrome_style": true
          // Not recommended; only provided for backwards compatibility,
          // and will be unsupported in a future version of Chrome (TBD).
          //"open_in_tab": true
      },
      "web_accessible_resources": [

    "images/faceblock.jpg",
    "images/seigaiha.png",
    "js/popup.js",
    "icon.png",
    "js/options.js",
    "css/popup.css",
    "popup.html",
    "options.html"
  ]
    }

提前致谢

尼尔斯·维梅伦

EDIT: I now have the following with the same problem

Background.js

  chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
      sendResponse({msg: "Element " + sender.element + " zijn zichtbaarheid wordt nu: " + sender.checked});

      return true;


  });

Popup.js

function getCurrentTabUrl(callback) {

  return new Promise(function (resolve, reject) {
    // https://developer.chrome.com/extensions/tabs#method-query
    var queryInfo = {
      active: true,
      currentWindow: true
    };

    chrome.tabs.query(queryInfo, function (tabs) {
      if (callback(tabs[0].url)) {
        return resolve();
      } else {
        return reject();
      }
    });
  });
}

function changeFacebook(data) {
  console.log(data);
  chrome.runtime.sendMessage(
    "changeFacebook",
    data,
    function (response //undefined) {
      console.log(response.msg); // UNDEFINED

    });
}






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


  var callback = function getCurrentTab(tab) {
    if (tab == "https://www.facebook.com/") {
      return true;
    } else {
      return false;
    }

  }


  getCurrentTabUrl(callback).then(function () {
    alert('on facebook');
    $('.section').hide();

  }, function () {
    alert('not on facebook');
  });


  $("input[type='checkbox']").on('change', function () {
  var id = $(this).attr('id');
  var check = this.checked;

  var data = {
    'element': id,
    'checked': check
  };

  changeFacebook(data);
});

  $('.menuItem').hide();

  $('.menuItem:first').show();

  jQuery('.navitem').on('click', function () {

    var value = $(this).html().toLocaleLowerCase();
    jQuery('.menuItem').hide();
    jQuery('#' + value).show();

  });
});

最佳答案

根据这里的文档:

https://developer.chrome.com/extensions/runtime#event-onMessage

在你的background.js中,应该是

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  ... 
});

由于您缺少最后一个参数,因此您真正拥有的是:

chrome.runtime.onMessage.addListener(function (request, sender) {
  ...
});

因此您的代码几乎重命名为 request => sendersender => sendResponse

因此,您正在尝试将 sender 作为函数调用。但实际的 sendResponse 回调函数是未定义的。如果您检查您的背景页面(请参阅有关如何操作的提示),您应该会看到该错误。

提示:

在开发 chrome 扩展时,如果有任何后台页面正在运行,您可以在 chrome://extensions 页面中 Inspect views: background page

打开弹出窗口后,您可以像往常一样检查弹出页面。

而且您可以随心所欲地放置调试器,并且可以随意使用它。

编辑:

所以我已经测试了您的代码,正如我上面所说,问题只是缺少参数。我还注意到文档说前两个参数是可选的(不确定那是什么模糊)。但是,如果您将代码更改为如下所示,它将起作用。

Background.js

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  var resp = {'navURL': "Not set yet"};
  if (request.greeting === "GetURL") {
    sendResponse(resp);
  }
});

Popup.js

function getURL() {
  chrome.runtime.sendMessage({
    greeting: "GetURL"
  },
  function (response) {
    console.log(response);
    alert(response.navURL);
  });
}

测试一下

  1. 转到后台页面检查,并粘贴后台页面片段。
  2. 转到弹出页面检查(打开您的弹出窗口,在弹出窗口中右键单击,然后选择检查)
  3. 粘贴弹出页面片段
  4. 在弹出页面检查中,调用getURL()

关于javascript - Chrome 插件消息传递回调未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41666679/

相关文章:

google-chrome-extension - 单击工具栏图标时在新选项卡中打开 chrome 扩展程序

javascript - jQuery 选择器 : how can I specify one select menu when I have more than one?

javascript - Javascript 循环内的闭包

php - 创建图像网格

javascript - 如何防止 chrome 扩展在同一弹出窗口仍然打开时重新打开它?

javascript - 为什么我的 localStorage 复选框/ bool 值比较不适用于我的 Google Chrome 扩展程序?

javascript - 在文本区域中以不同颜色突出显示字符串

javascript - 防止 Atom Beautify 自动格式化 es6 导入/对象解构 (React)

javascript - 尽管在 JS 中处理了失败,但 Chrome 报告请求失败

javascript - Phonegap iOS getjson 不工作 - 但在桌面工作