chrome扩展:堆栈跟踪:TypeError:不能读取属性'selectedtext'的定义

chrome extension: Stack trace: TypeError: Cannot read property 'selectedtext' of undefined

本文关键字:定义 属性 selectedtext 不能读 堆栈 扩展 跟踪 TypeError chrome 不能 读取      更新时间:2023-09-26

my contentscript.js:

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
   if (request.ask === "selectedtext"){
    sendResponse({selectedtext: window.getSelection().toString()});
   }      
});

my background.js:

function onClickHandler(info, tab) {
 chrome.tabs.sendMessage(tab.id, {ask: "selectedtext"}, function(response) {
   console.log(response.selectedtext);
 });
};
chrome.contextMenus.onClicked.addListener(onClickHandler);
chrome.runtime.onInstalled.addListener(function() {
  var contexts = ["selection"];
  for (var i = 0; i < contexts.length; i++){
    var context = contexts[i];    
    var title = "send the word to background.js";
    var id = chrome.contextMenus.create({"title": title, "contexts":[context],"id": "context1" + context});   
  } 
});

:

{
"name" : "Send Data Plugin",
"version" : "1.1",
"description" : "A trivial usage example.",
"permissions": [
  "browsingData", "contextMenus", "http://chromeplugin.sites.djangoeurope.com/"
],
"browser_action": {
  "default_icon": "icon.png",
  "default_popup": "popup.html"
},  
"background": {
  "persistent": false,
  "scripts": ["background.js"]
},
"manifest_version": 2,
"content_scripts": [{
  "matches": ["<all_urls>"],
  "js": ["contentscript.js"]
 }]
}

但是,一旦我点击contextMenu send the word to background.js,我在控制台得到错误:

Stack trace: TypeError: Cannot read property 'selectedtext' of undefined

我做错了什么?我在谷歌上搜索并阅读了一些问题,但似乎没有帮助…

你的错误意味着你得到未定义的响应。即没有数据从上下文页面返回。

你的content.js看起来很好,我认为最有可能的事情是没有内容脚本从另一端通信。在你的内容脚本中添加一个console.log,并确保它被击中。

您可能只需要刷新您正在通信的页面,因为内容脚本可能不是当前的?