Using JavaScript to force clicks on external anchor links and external image links to open in new tab/window and internal links in same window
In my on-going Barebones Blogger Blog Feed to HTML Book program, I faced a problem of blogbook window dynamic contents being lost when user clicked on external links in blogbook. Solution was to force external anchor and external image links to open in new tab/window but open internal links in same tab/window using JavaScript. The current version of the JavaScript code in the blogbook HTML page is given below:
<script>
// External links should be opened in new tab/window as otherwise dynamic HTML
// of this tab/window will be lost.
// But internal links should be opened in this tab/window.
document.body.addEventListener("click", function (e) {
if (e.target && e.target.nodeName == "A") {
const linkhref = e.target.href;
const docURL = document.URL;
let docURLBase = docURL;
const hashCharIndex = docURL.indexOf("#");
if (hashCharIndex === 0) {
console.log("Unexpected positon of # char as 0 in document URL");
} else if (hashCharIndex > 0) {
docURLBase = docURL.substring(0, hashCharIndex);
}
if (!linkhref.includes(docURLBase)) {
e.target.target = "_blank";
}
} else if (e.target && e.target.nodeName == "IMG") {
// console.log(e.target.currentSrc);
// let s = e.target.currentSrc;
// console.log(s);
// s += "?target=_blank";
// console.log(s);
// // Assigning to e.target.currentSrc is not changing its value!
// e.target.currentSrc = s;
// console.log(e.target.currentSrc);
e.preventDefault(); //this works and so we can open window in new tab
window.open(e.target.currentSrc); //works!
}
});
</script>
------
I need to update above code to check if image link is internal or external.
Comments
Post a Comment