未捕获的TypeError:无法读取属性'创建'在chrome扩展中未定义

时间:2018-05-10 01:51:11

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

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

background.js

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

但这可能不是安慰,因为甚至没有调用此块。

这是代码

manifest.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
  },

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

  

未捕获的TypeError:无法读取属性&#39;创建&#39;未定义的

1 个答案:

答案 0 :(得分:0)

对于您的消息传递部分,您的问题应该是您正在使用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);
  });

您可以在此处详细了解:documentation

此外,对于您正在使用的chrome命令api,您希望在后台处理命令,如下所示:

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

而不是到处处理消息的麻烦。

在此处阅读:https://developer.chrome.com/apps/messaging