Alert User When Clicking On 3rd Party Link

Posted By: Ian on Jan 10, 2013 in JQuery
Last modified on June 27th, 2016 at 9:32 pm,

Recently i was asked to come up with a script to alert the End User when they were leaving a website when they clicked on an external link and this is what i came up with after finding a similar script which opens all external links into a new window.

Whilst opening external links into a new window is ok a lot of people believe it is up to the End User to decide if they want to open a new window or not.

If you read the Privacy Policy of a lot of websites especially the bigger ones it clearly states that they have no control over 3rd party links and you go there at your own risk blah blah blah.
But how many people actually read these Policies? Exactly! So this is why this script alerts the user and gives them a choice.
Because some people own and operate more than one website this script enables you to add as many ‘friendly’ websites from which you control and then as longs the link starts http:// or https:// and is not in the friendly list shows the confirmation box.

    jQuery(function ($) {

        // trusted websites which we own
        friendly = '[href*=""],[href*=""]';

        // if a link starts http: // or https:// and is not on our friendly list and is clicked on
        $('a[href^="http://"],a[href^="https://"]').not(friendly).click(function (event) {

            // store link clicked on in variable
            var url = $(this).attr('href');

            // prevent default action(Links working in this case)

            // set the confirmation message
            var confirm_box = confirm('You are about to visit a third party website over which we have no control.');

            // if the confirmation is true(user clicks ok) direct the browser to the link 's url
            if (confirm_box) {
                window.location = url;

        }); // end click(function
    }); // end jQuery(function




Did this help you? Please Let me know by commenting below even if it’s just to say “Thanks”

Discussion - 2 Comments

  • Justin McElvaney Justin McElvaney Apr 11, 2016 

    The script above I have working great (thank you!) but I am also trying to add the new window bit linked above. When the user clicks OK to continue I’d like that link to open in a new window and no matter where or how I add that functionality it does not work. The exception was adding it before the above script which resulted in the message portion being disregarded.


leave a comment

About This Site

Dreams are built from lines of code well it's true!
If you can dream it you can usually code it.

I have learned so much from other people on the Internet and this site is for me to give back some of what i have learned and hope people can now learn from me.
Have fun and surf safely,

protected by copyscape duplicate content check


Powered by Banner Bar 125