Select external links with JavaScript

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
});

});

1 Like

Hello, @Jeff_Garver

To achieve your goal of opening a lightbox for all external links on your Wix website, you can adjust your JavaScript code slightly. Here’s an improved version that should work:

import wixWindow from ‘wix-window’;
import wixLocation from ‘wix-location’;

$w.onReady(() => {
// Select all links on the page
const allLinks = $w(‘a’); // This selects all anchor 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 });
        });
    }
});

});

Lightbox Code

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
});

});

Explanation:
Selecting Links: The selector $w(‘a’) selects all anchor elements ( a tags)
on the page. This should capture all links, including those inside repeaters.

Checking External Links: The code checks if the link URL does not include the base URL of your site, identifying it as an external link.

Opening Lightbox: When an external link is clicked, it opens a lightbox named ‘external-notice’ and passes the external URL to it.
Tips:
Ensure the lightbox ID ‘external-notice’ matches the lightbox you created in Wix.

If you have any specific classes or IDs for links, you can adjust the selector accordingly.

This approach should help you manage all external links across your site, including those within repeaters, without needing to assign unique IDs to each link.

I hope this info is helpful to you.

Best Regard,
Jennifer Anderson

Thanks for this but it didn’t work.

Wix gives an error: ‘a’ is not a valid selector.

Alright, so you have a repeater. In the repeater there is a button with either an internal link or an external link.

And when that button is clicked you want to check if link is internal so that the page can proceed to load OR if it is external to prompt a lightbox that alerts the user that they are about to leave the website. And in that lightbox they can either proceed to leave the website or cancel to close the lightbox.

Got it!

Let’s trim down your code and rearrange your code to fit this logic.

First you have to check that the repeater items are ready, then check the URL for that specific item and handle the match or mismatch accordingly when a button is clicked.

This is just a sample code how to work with repeater elements, so you will need to modify it to match your actual URL / fieldkeys, etc.

import wixWindowFrontend from 'wix-window-frontend';
import wixLocationFrontend from "wix-location-frontend";


$w.onReady(function () {

    let isInternal = wixLocationFrontend.baseUrl;

    $w("#myRepeater").onItemReady(($item, itemData, index) => {

        if (itemData.linkURL && itemData.linkURL.includes(isInternal)) {

            //if it is internal proceed to link
            $item("#thisRepeaterButton").onClick((event) => {
                wixLocationFrontend.to(itemData.linkURL);
            });

        } else {

            //if it is not internal proceed to lightbox
            $item("#thisRepeaterButton").onClick((event) => {
                wixWindowFrontend.openLightbox('external-notice', { url: itemData.linkUrl });
            });
        }
    });

});

https://dev.wix.com/docs/velo/api-reference/$w/repeater/on-item-ready

https://dev.wix.com/docs/velo/api-reference/$w/button/on-click

https://dev.wix.com/docs/velo/api-reference/wix-location-frontend/to

https://dev.wix.com/docs/velo/api-reference/wix-window-frontend/open-lightbox

Happy Coding!

Love,

Code Queen

Yes this will help you .

Thanks