Skip to content

Commit

Permalink
Issue#946 open links in new tab (#1009)
Browse files Browse the repository at this point in the history
I added two helper functions that are called inside the editor's `render` method.

`openLinksInNewTab` prevents the default click event on external links (all anchors with an `href` attribute that starts with `http`) and opens them in a new tab.

While I was at it, I stumbled upon the issue that relative links (like `<a href="#someanchor">`) also didn't work. I didn't find a ticket for that so I thought it would make sense to fix in the scope of this ticket.

`scrollToAnchors` prevents the default click event on relative links and scrolls the targeted anchor into view.

I hope that the code structure adheres to your quality standards.
  • Loading branch information
stephanmax authored and Schalk Neethling committed Jul 4, 2018
1 parent c977bc4 commit 4e13100
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
27 changes: 27 additions & 0 deletions js/editor-libs/mce-utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,19 @@ module.exports = {

return tmpElem.style[property] !== undefined;
},
/**
* Interrupts the default click event on external links inside
* the shadow dom and opens them in a new tab instead
* @param {Array} externalLinks - all external links inside the shadow dom
*/
openLinksInNewTab: function(externalLinks) {
externalLinks.forEach(function(externalLink) {
externalLink.addEventListener('click', function(event) {
event.preventDefault();
window.open(externalLink.href);
});
});
},
/**
* Posts a name to set as a mark to Kuma for
* processing and beaconing to GA
Expand All @@ -45,6 +58,20 @@ module.exports = {
postToKuma: function(perf) {
window.parent.postMessage(perf, 'https://developer.mozilla.org');
},
/**
* Interrupts the default click event on relative links inside
* the shadow dom and scrolls to the targeted anchor
* @param {Object} shadow - the shadow dom root
* @param {Array} relativeLinks - all relative links inside the shadow dom
*/
scrollToAnchors: function(shadow, relativeLinks) {
relativeLinks.forEach(function(relativeLink) {
relativeLink.addEventListener('click', function(event) {
event.preventDefault();
shadow.querySelector(relativeLink.hash).scrollIntoView();
});
});
},
/**
* Hides the default example and shows the custom block
* @param {object} customBlock - The HTML section to show
Expand Down
2 changes: 2 additions & 0 deletions js/editor.js
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,8 @@

shadow.appendChild(document.importNode(content, true));
setOutputHeight(shadow.querySelector('div'));
mceUtils.openLinksInNewTab(shadow.querySelectorAll('a[href^="http"]'));
mceUtils.scrollToAnchors(shadow, shadow.querySelectorAll('a[href^="#"]'));
}

/**
Expand Down

0 comments on commit 4e13100

Please sign in to comment.