javascriptexeccommand

Adding a target="_blank" with execCommand 'createlink'


I am attempting to create a mini WYSIWYG editor for a custom CMS. It has the option to add and remove links. It adds links fine, but would like to have the option to add target="_blank" to the hyperlink. Also, if possible, I would like to be able to add alt="" and title="".

At the moment this is my code:

function addLink() {
    var linkURL = prompt('Enter a URL:', 'http://');
    editorWindow.document.execCommand('createlink', false, linkURL);
}

Been looking around, and can't seem to find a solution. Most of the solutions I've seen say to add:

function addLink() {
    var linkURL = prompt('Enter a URL:', 'http://');
    var newLink = editorWindow.document.execCommand('createlink', false, linkURL);
    newLink.target = "_blank";
}

But this doesn't seem to work. Any suggestions?


Solution

  • 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...