Question:
How can I use JavaScript to have all external links open a lightbox that lets website visitor know they are about to leave the site?
Product:
Wix Studio Editor.
What are you trying to achieve:
I have had success in calling up the lightbox by individually targeting buttons that have an external link by giving them a unique ID in the properties panel and then using JavaScript to open a lightbox and then passing the URL to the ‘ProceedButton.’
I’ve been able to achieve the result that I want by using this code and targeting each button by giving it a unique ID. But I can’t give buttons in a repeater a unique ID. I want to be able to do this for my whole website which has hundreds of sections that are done as repeaters.
I tried to write JavaScript that will target all external links but it doesn’t work and I’m not sure why.
Here is the code I’m trying to use but isn’t working. I’ve tried using this code on a specific page and also on masterPage.js.
import wixWindow from ‘wix-window’;
import wixLocation from ‘wix-location’;
$w.onReady(() => {
// Select all links on the page
const allLinks = $w(‘Link’); // This selects all Wix Link elements
console.log(‘All Links:’, allLinks);
// Loop through the links and check if they are external
allLinks.forEach((link) => {
const linkUrl = link.href; // Get the href value
// Check if the link is external
if (linkUrl && !linkUrl.includes(wixLocation.baseUrl)) {
console.log('External link detected:', linkUrl);
link.onClick((event) => {
event.preventDefault(); // Prevent default navigation
console.log('Opening external link in lightbox:', linkUrl);
wixWindow.openLightbox('external-notice', { url: linkUrl });
});
}
});
});
Here’s the code that goes in the lightbox:
import wixWindow from ‘wix-window’;
import wixLocation from ‘wix-location’;
$w.onReady(() => {
// Get the data passed to the lightbox
const receivedData = wixWindow.lightbox.getContext();
const externalUrl = receivedData.url;
// Redirect to the external URL on clicking "Proceed"
$w('#proceedButton').onClick(() => {
wixLocation.to(externalUrl); // Redirect to the external URL
});
// Close the lightbox on clicking "Cancel"
$w('#cancelButton').onClick(() => {
wixWindow.lightbox.close(); // Close the lightbox
});
});