简体   繁体   中英

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

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});   
  } 
});

UPDATE :

{
"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"]
 }]
}

but, once I click on contextMenu send the word to background.js , i am getting the error in console:

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

what am i doing wrong? i googled and read some q&a's in here, but none seems to be helping..

Well your error means that you're getting undefined as your response. ie no data is coming back from the context page.

Your content.js looks fine, I think the most likely thing is there is no content script communicating from the other end. Put a console.log in your content script and make sure that's being hit.

You may just need to refresh the page that you're communicating with as the content script may not be the current one?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM