Adding a target=“_blank” with execCommand 'createlink'

不打扰是莪最后的温柔 提交于 2019-12-04 02:53:19
thelos999

I was able to find a solution. Don't know if this is the right way to go, but it works. Following 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 in case anyone else is looking and stumbles upon this...

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

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

Since, there is no straightforward cross-browser solution, one cross-browser workaround could be programatically attaching an event handler 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');
      }); 
});

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

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

//reselecting:
window.getSelection().addRange(sel);

//link:
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 like a charm. And this simplicity ^^

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

document.designMode = "on";

Then the following should work:

var url = 'http://google.com';
var selection = document.getSelection();
document.execCommand('createLink', true, url);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!