In the previous post, we get the selected html, but usually we also need convert the relative link to absolute path.
The Code
Tested in Chrome:
The Code
Tested in Chrome:
var thisPageUrl = stripQueryStringAndHashFromPath(window.location.href); function stripQueryStringAndHashFromPath(url) { return url.split("?")[0].split("#")[0]; } var hrefPattern = /href="([^"]*)"/; function changeToAbsoluteUrl(linkElement) { var outerHTML = linkElement.outerHTML; var match= outerHTML.match(hrefPattern); if(match!=null) { var href= match[1]; linkElement.href= thisPageUrl + href; } } function parseSelection() { var selection = window.getSelection(); if(selection.rangeCount > 0) { // please get source code of getSelectionHtml from // http://lifelongprogrammer.blogspot.com/2014/05/javascript-get-selected-html-in-webpage.html var selectedHtml = getSelectionHtml(selection); var parser = new DOMParser() var selectedDoc = parser.parseFromString(selectedHtml, "text/html"); var elements = selectedDoc.getElementsByTagName("a"); var arrayLength = elements.length; for (var i = 0; i < arrayLength; i++) { var element = elements[i]; changeToAbsoluteUrl(element); } selectedHtml = selectedDoc.getElementsByTagName("body")[0].innerHTML; console.log("selectedHtml: " + selectedHtml); } } parseSelection();