I have made a thing in NW.js. By default, any hyperlinks that the user can click on opens in a new NW.js browser window.
I'm trying to make it so that some (not all or none!) of these open in the system browser instead. It is important that these are <a>
elements; not JavaScript function calls.
Reading on this page: https://nwjs.readthedocs.io/en/latest/References/Window/#event-new-win-policy-frame-url-policy
... I was able make it so that all hyperlinks open in the system browser. But I only want this for some. I want to specify an attribute or something, such as <a some-attribute="open-in-system-browser"...>
which can be checked in the code:
nw.Window.get().on('new-win-policy', function(frame, url, policy)
{
policy.ignore();
nw.Shell.openExternal(url);
});
What am I missing? If it can be avoided, I don't want to "parse the url" to determine this, as it's ugly and messy. Both "frame" and "policy" seem like useless parameters.
You don't need to do anything special, it works that way by default. Everything opens in NW.js directly unless you specifically tell it to open in the default browser.
There are many ways to do this, but a simple example would be
<div>
<a href="about.html">About</a>
<a href="thing.html">Thing</a>
<a href="https://example.com" data-external-link>Example</a>
<a href="https://stackoverflow.com" data-external-link>Stackoverflow</a>
</div>
Vanilla JS
// Find all elements on the page
var externalLinks = document.querySelectorAll('[data-external-link]');
// Convert the node list to an array
externalLinks = Array.from(externalLinks);
// loop over each link
externalLinks.forEach(function (link) {
// add a click event listener to each link
link.addEventListener('click', function (evt) {
// Do not navigate to the link in NW.js
evt.preventDefault();
// get the URl for the clicked link
var url = evt.currentTarget.href;
// Open the url in the default browser
nw.Shell.openExternal(url);
});
});
or the jQuery version
$('[data-external-link]').click(function (evt) {
evt.preventDefault();
nw.Shell.openExternal(evt.currentTarget.href);
});