Last active
December 22, 2015 02:29
-
-
Save szwacz/6403632 to your computer and use it in GitHub Desktop.
node-webkit: General solution for opening links in system default browser. Useful if you have a lot of links to deal with.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<body> | |
<script> | |
var gui = require('nw.gui'); | |
function supportExternalLinks(event) { | |
var href; | |
var isExternal = false; | |
function crawlDom(element) { | |
if (element.nodeName.toLowerCase() === 'a') { | |
href = element.getAttribute('href'); | |
} | |
if (element.classList.contains('js-external-link')) { | |
isExternal = true; | |
} | |
if (href && isExternal) { | |
gui.Shell.openExternal(href); | |
event.preventDefault(); | |
} else if (element.parentElement) { | |
crawlDom(element.parentElement); | |
} | |
} | |
crawlDom(event.target); | |
} | |
document.body.addEventListener('click', supportExternalLinks, false); | |
</script> | |
<p> | |
Every link with class <b>.js-external-link</b> will be opened | |
in external browser.<br/> | |
<a class="js-external-link" href="http://google.com">google</a> | |
</p> | |
<p class="js-external-link"> | |
The same behaviour for many links can be achieved by adding | |
this class to any parent tag of an anchor tag.<br/> | |
<a href="http://google.com">google</a> | |
<a href="http://bing.com">bing</a> | |
</p> | |
<p> | |
Links without this class are opened as always.<br/> | |
<a href="http://google.com">google</a> | |
</p> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment