How to make a bookmarklet that turns the selected text into a link?

Let's say you

  • select "some text" in the browser.
  • Click Bookmarklet
  • the selected text turns into a simple link with the URL of the current page.

How to implement this?

+3
source share
2 answers

Sample code tested in Firefox 3.6, Chome 6, and Opera 10.6 that does exactly what you described in your question.

javascript:(
    function(){
        var range = window.getSelection().getRangeAt(0);
        var a = document.createElement('a');
        a.setAttribute('href',document.location);
        a.appendChild(document.createTextNode(window.getSelection().toString()));
        range.deleteContents();
        range.insertNode(a);
    }
)()

If you need it to be compatible with IE, read this post: http://www.daniweb.com/forums/thread85642.html

+2
source

@wojtiku, IE :

javascript:(function() {
    var sel, range, a;
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.rangeCount) {
            range = sel.getRangeAt(0);
            a = document.createElement("a");
            a.href = window.location.href;
            a.appendChild(document.createTextNode("" + sel));
            range.deleteContents();
            range.insertNode(a);
        }
    } else if (document.selection && document.selection.type == "Text") {
        range = document.selection.createRange();
        a = document.createElement("a");
        a.href = window.location.href;
        a.appendChild(document.createTextNode(range.text));
        range.pasteHTML(a.outerHTML);
    }
})();
+1

Source: https://habr.com/ru/post/1773519/


All Articles