Alexander Ivanov
Alexander Ivanov

Reputation: 532

Can I find the tag with selected text in a chrome extension?

If I have added a item in the context menu :

chrome.contextMenus.create({
"title" : chrome.i18n.getMessage("right_click") ,
"type" : "normal",
"contexts" : ["selection"],
"onclick" : my_function() // returns a callback function
});

How can I get the tag with the selected content. (the selection is part of its innerHTML i guess)

EDIT : my_function is a factory function : it returns an event handler.

Upvotes: 1

Views: 294

Answers (1)

anfilat
anfilat

Reputation: 706

You can inject a content script and ask a selection from the script.

content.js:

function getSel() {
  //get text
  var sel = window.getSelection().toString();
  //or get parent tag for selection
  //var sel = window.getSelection().getRangeAt(0).commonAncestorContainer;
  if (sel) {
    chrome.extension.sendRequest({
      msg: 'data',
      sel: sel
    });
  };
};

background.js:

var selText;

function onClickFunction(info, tab) {
  chrome.tabs.executeScript(
    tab.id,
    {code: 'getSel()', allFrames: true},
    function () {
      //do anything with selText
    }
  );
};

chrome.extension.onRequest.addListener(function (request, sender, response) {
  if (request.msg == 'data') {
    selText = request.sel;
  };
};

Upvotes: 2

Related Questions