【问题标题】:Uncaught TypeError: Cannot read property 'create' of undefined in chrome extension未捕获的类型错误:无法读取 chrome 扩展中未定义的属性“创建”
【发布时间】:2018-10-20 05:16:58
【问题描述】:

我正在尝试开发 chrome 扩展,当用户选择文本时,将抓取所选文本,然后发送到后台脚本以处理 api 调用。现在,文本已被抓取,但我在以下行中得到了安慰

背景.js

chrome.extension.onMessage.addListener(function(request, sender, sendResponse){
    console.log('req', request.message)

但这并没有得到安慰,也许是因为这个块甚至没有被调用。

这里是代码

ma​​nifest.json

{
  "manifest_version": 2,
  "name": "DEMO",
  "description": "This extension allow the user to select the text and redirect to the google to search that text",
  "version": "1.0",
  "browser_action": {
    "default_icon": "Logo.png",
    "default_popup": "html/popup.html",
    "default_title": "click me"
  },
  "permissions": [
    "activeTab",
    "storage"
  ],
  "options_page": "html/popup.html",
  "background": {
    "scripts": ["js/eventPage.js", "js/background.js"],
    "persistent": false
  },
  "content_scripts": [
    {
        "matches" : [
            "http://*/*", "https://*/*"
        ],
        "js" : [
            "js/content.js"
        ]
    }
],
  "commands": {
          "toggle-feature-foo": {
            "suggested_key": {
              "default": "Ctrl+Shift+Y",
              "mac": "Command+Shift+H"
            },
            "description": "Toggle feature foo"
          }
        }
}

content.js

function init(event) {
  var topic = "";
  if (window.getSelection) {
    topic = window.getSelection().toString();
  } else if (document.selection) {
      topic = document.selection.createRange().topic;
  } else {
    return topic;
  }
  if((event.ctrlKey && event.keyCode === 65) && topic.length) {
    chrome.extension.sendMessage({'message': 'setTopic', 'data': topic}, function(response){
      console.log('response', response);
    })
  }
}

document.addEventListener('keydown',init);

background.js

var selectedTopic = null;

  chrome.extension.onMessage.addListener(function(request, sender, sendResponse){
    console.log('req', request.message) // not listened 
    switch(request.message) {
      case 'setTopic':
        window.selectedTopic = request.data;
      break;
      default:
        sendResponse({data: 'Invalid'})
      break;
    }
  })

  function savetopic(info, tab) {
    var httpRequest = new XMLHttpRequest();
    httpRequest.open('get', 'http://www.google.com/?q='+selectedTopic)
    httpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    httpRequest.onreadystatechange = function() {
    if(httpRequest.readyState==4) {
      alert(httpRequest.responseText);
    }
  }
}

var contexts = ["selection"];
for (var i = 0; i < contexts.length; i++)
{
    var context = contexts[i];
    chrome.contextMenus.create({"title": "Send to Google", "contexts":[context], "onclick": savetopic});
}

这是我的 chrome 扩展的完整代码。我错过了 background.js 中的某些内容吗?我什至在 manifest.json 中作为

"background": {
    "scripts": ["js/eventPage.js", "js/background.js"],
    "persistent": false
  },

为什么它不起作用?我从扩展设置的检查视图中检查了后台,它在控制台中显示以下错误

未捕获的类型错误:无法读取未定义的属性“创建”

【问题讨论】:

  • 阅读documentation 您必须在应用的清单中声明“contextMenus”权限才能使用API​​ ...您这样做了吗? (提示:你没有:p)
  • 你需要"permissions": [ "activeTab", "storage", "contextMenus" ],
  • 我已授予权限,但未显示上下文菜单,因此我得到未定义的响应。
  • 别忘了重新加载扩展。
  • 我已经重新加载了。

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


【解决方案1】:

对于您的消息传递部分,您的问题应该是您正在使用 chrome.extension.onMessage 和 chrome.extension.sendMessage。

对于 chrome 中的消息传递,您可以这样做:

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    console.log('req', request.message) // not listened 
    switch(request.message) {
     case 'setTopic':
      window.selectedTopic = request.data;
      break;
     default:
      sendResponse({data: 'Invalid'})
      break;
    }
  });

chrome.runtime.sendMessage({'message': 'setTopic', 'data': topic}, function(response){
  console.log('response', response);
  });

您可以在此处阅读更多信息:https://developer.chrome.com/apps/messaging

此外,对于您正在使用的 chrome commands api,您希望像这样在后台处理命令:

chrome.commands.onCommand.addListener(function(command) {
        console.log('Command:', command);
      });

而不是到处做消息传递的麻烦。

在这里阅读:https://developer.chrome.com/apps/commands

【讨论】:

  • 它仍然没有被监听所以 selectedTopic 也为空。
  • 您可能还想在权限中添加“背景”并在后台部分设置 persistent : true
  • 你的意思是像这样的“背景”:{“脚本”:[“js/background.js”],“持久”:真}?
  • 是的,因为您希望背景始终在列表中
  • 您是否测试过问题是否不在消息中。也许这与您处理点击的方式有关
猜你喜欢
  • 2017-10-28
  • 1970-01-01
  • 2021-06-07
  • 2013-02-13
  • 2016-01-03
  • 1970-01-01
  • 2016-03-26
  • 2021-04-20
  • 1970-01-01
相关资源
最近更新 更多