[英]Uncaught TypeError: Cannot read property 'getSelected' of undefined (Chrome-Extension )
[英]chrome extension: Stack trace: TypeError: Cannot read property 'selectedtext' of undefined
我的contentscript.js:
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.ask === "selectedtext"){
sendResponse({selectedtext: window.getSelection().toString()});
}
});
我的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
我究竟做错了什么? 我用Google搜索并在这里阅读了一些q&a,但似乎没有人帮助..
那么你的错误就意味着你的回答是未定义的。 即没有数据从上下文页面返回。
你的content.js看起来不错,我认为最可能的是没有内容脚本从另一端进行通信。 在您的内容脚本中放入console.log并确保它被击中。
您可能只需要刷新与之通信的页面,因为内容脚本可能不是当前的脚本?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.