0

I want to get URL of selected links in my chrome extension (detect links in selected text and give me urls)

my code for getting selected text in background.js is :

function SetLinks(info, tab) {
    alert(info.selectionText);
}

my extension must get the url of selected text (detect links in selected text), how can i do it ?

how should extension work: user highlighted a text in browser, when he clicks on our option on context menu, my extension must detect links, and give user the URLs

i tried to get selected DOM with this code in javascript :

function getHTMLOfSelection() {
    function getHTMLOfSelection () {
      var range;
      if (document.selection && document.selection.createRange) {
        range = document.selection.createRange();
        return range.htmlText;
      }
      else if (window.getSelection) {
        var selection = window.getSelection();
        if (selection.rangeCount > 0) {
          range = selection.getRangeAt(0);
          var clonedSelection = range.cloneContents();
          var div = document.createElement('div');
          div.appendChild(clonedSelection);
          return div.innerHTML;
        }
        else {
          return '';
        }
      }
      else {
        return '';
      }
    }

}

but here is a problem with selection.rangeCount it will return 0

in html file that is created to test the function, it works fine. but not in chrome extension

Mehdi Nazari
  • 113
  • 2
  • 13
  • Define "selected link". Link selected as text? – Xan Apr 02 '15 at 13:13
  • let me tell it this way: user highlighted a text in browser, when he clicks on our option on context menu, my extension must detect links, and give user the URLs – Mehdi Nazari Apr 02 '15 at 13:16
  • All links within the selection? You should add that to the question to clarify it. – Xan Apr 02 '15 at 13:17
  • This question will probably answer it: http://stackoverflow.com/questions/28211174/get-selection-dom-in-chrome-extension-contextmenu – Xan Apr 02 '15 at 13:19
  • that link wasn't the answer for me, there is a problem with window.getSelection(); function in chrome extesnion. i'll update the question – Mehdi Nazari Apr 02 '15 at 14:08
  • Well, it's one of the required steps. – Xan Apr 02 '15 at 14:09
  • sure it is. but need more details – Mehdi Nazari Apr 02 '15 at 14:09
  • You haven't read the question I linked carefully. This must execute in a content script within the tab, not in your background page. – Xan Apr 02 '15 at 14:14

0 Answers0