Tolga Ozses
Tolga Ozses

Reputation: 355

Cannot send message to content script properly

I'm so close to finishing my Chrome extension. I have one or two things to do. One of them is sending a message from the content script to the background script. I wrote the following, but it doesn't quite what I want.

content.js

var a=document.getElementsByTagName('a');
for (i=0,len=a.length;i<len;i++) {
  a[i].addEventListener('contextmenu', function() {
    var linkTitle = this.getAttribute('title').trim();
    var linkUrl = this.getAttribute('href');
    if ((linkTitle != null) && (linkTitle.length > 0)) {
      chrome.extension.sendMessage({action:'bookmarkLink', 'title':linkTitle, 'url': linkUrl}, function(msg) {
        alert('Messages sent: '+action+' and '+linkTitle+' also '+linkUrl);
      });
    }
  });
};

background.js

chrome.contextMenus.create({'title': 'Add to mySU bookmarks', 'contexts': ['link'], 'onclick': mySUBookmarkLink});

function mySUBookmarkLink(info, tab) {
  chrome.extension.onMessage.addListener(function(msg, sender, sendResponse) {
    if (msg.action == 'bookmarkLink') {
      chrome.storage.sync.set({'title': msg.linkTitle, 'url': msg.linkUrl}, function(msg) {
        alert('Saved '+msg.linkTitle+' to bookmarks');
      });
    } 
  });
};

My problems are:

  1. In the first code block, it alerts Saved undefined to bookmarks as soon as I right click on the link, while as I understand it should only send a message on right click and the second code block should alert Saved to bookmarks when I click on the context menu. What am I missing or doing wrong?
  2. I may not have used parameters correctly (I am fairly new to extension development and Javascript in general). Do the above look okay?

Thank you in advance,

K.

Upvotes: 0

Views: 120

Answers (2)

user3307259
user3307259

Reputation:

it's JSON-serializable messaging, where first pair is for recognition, and then followed by pairs of
key: value.
You pull the value from received message by calling it's key.

is should be:

alert('Saved '+msg.title+' to bookmarks');

or even better:

function mySUBookmarkLink(info, tab) {
  chrome.extension.onMessage.addListener(function(msg, sender, sendResponse) {
    if (msg.action == 'bookmarkLink') {
      var receivedValue = msg.title; //pull it out first, for better overview
      chrome.storage.sync.set({'title': msg.title, 'url': msg.url}, function(msg) {
        alert('Saved '+receivedValue+' to bookmarks');
      });
    } 
  });
};

Upvotes: 0

devnull69
devnull69

Reputation: 16574

It's chrome.runtime.sendMessage and chrome.runtime.onMessage rather than chrome.extension.

There used to be chrome.extension.sendRequest and chrome.extension.onRequest which have been deprecated in favor of the chrome.runtime API methods mentioned above.

See Chrome Extensions - Message Passing

Upvotes: 2

Related Questions