[ACCEPTED]-Adding a target="_blank" with execCommand 'createlink'-execcommand

Accepted answer
Score: 24

I was able to find a solution. Don't know 4 if this is the right way to go, but it works. Following 3 https://stackoverflow.com/a/5605841/997632, this is what I used for my code to work:

function addLink() {
    var linkURL = prompt('Enter a URL:', 'http://');
    var sText = editorWindow.document.getSelection();

    editorWindow.document.execCommand('insertHTML', false, '<a href="' + linkURL + '" target="_blank">' + sText + '</a>');

Just 2 in case anyone else is looking and stumbles 1 upon this...

Score: 8

insertHTML can be frustrated if you have 2 a bold or italic before. I use the following 1 approach:

var url = 'example.com';
var selection = document.getSelection();
document.execCommand('createLink', true, url);
selection.anchorNode.parentElement.target = '_blank';
Score: 5

I know this thread is quite old, but let 12 me throw my 2 cents in, and maybe someone 11 will find this useful ;) I'm working on 10 a WYSIWYG editor too As I found the accepted 9 solution fails for me when I try to make 8 a link from a selected image in FF (the 7 getSelection().getRangeAt(0) returns the 6 image's parent div and treats the image 5 as it never wasn't there (this is how I 4 see it)), here's a dirty but working (and, I 3 think, it's turbo-cross-browser) idea I 2 came up with (jQuery):

//somewhere before losing the focus:
sel = window.getSelection().getRangeAt(0);


document.execCommand('createLink', false, 'LINK_TO_CHANGE');
$('a[href="LINK_TO_CHANGE"').attr('target', '_blank');
//any other attr changes here
$('a[href="LINK_TO_CHANGE"').attr('href', theRealHref);

Is it good idea? Works 1 like a charm. And this simplicity ^^

Score: 2

Since, there is no straightforward cross-browser 3 solution, one cross-browser workaround could 2 be programatically attaching an event handler 1 to a inside your editor:

var aLinks = Array.prototype.slice.call(editorElement.querySelectorAll('a'));
aLinks.forEach(function(link) {
      link.addEventListener('click', function() {
          window.open(link.href, '_blank');
Score: 0

Nobody seems to mention that as per specs, the 2 document has to be in the design mode:

document.designMode = "on";

Then the following 1 should work:

var url = 'http://google.com';
var selection = document.getSelection();
document.execCommand('createLink', true, url);
Score: 0

The execCommand'createLink' does not always work. It will sometimes 4 wrap the link text inside a link.

<a><a href="">label</a></a> 

Resulting 3 the html link code appearing in the document 2 and the link not working.

in this case ues 1 execCommand 'insertHTML'

 val=`<a href="`+val+`" target="_blank">`+label+`</a>`      
//document.execCommand('createLink', false, val);
 document.execCommand('insertHTML', false, val);

More Related questions