Verify Departure on External Links within Wordpress

Let me set the stage for you:

  • We're dealing with a bank website here. So, whenever a user wants to click on an external link (could be to a Facebook page or a partner website), we need to have a notification box pop up saying "You are about to leave this page, none of this content is managed by...etc.".

  • The user should then have the option to either click 'confirm' to open the external link in a new window or click 'cancel' to stay on the website and receive another message saying "you have chosen not to leave the site".

This particular site is built with Wordpress, so I'm on the hunt for an easy solution to manage this without having to manually add custom Javascript to each and every link.

I've seen it function smoothly on their current site: . I believe I can replicate it on the new site by incorporating a confirm_entry script in the header and applying customized Javascript to each link, but I'm struggling to make the links open in a new window.

This method is quite time-consuming as it requires individually editing all external links. Is there a simpler way to identify external links and apply this feature across the entire site? If not, what steps can I take to ensure the links open in a new window?

Check out the code snippet I'm currently using:

    <script type="text/javascript">
        <!--
            function confirm_entry(varible_value)
            {
            input_box=confirm("Link Disclaimer:  Bank Name  provides links to web pages which are not part of the Bank Name website or clearmountainbank.com or online.bankname.com domains. These sites are not under Bank Name control, and Clear Mountain Bank is not responsible for the information or links you may find there. Bank Name is providing these links only as a convenience. The presence of these links on any Bank Name website is not intended to imply Bank Name endorsement of that site, but to provide a convenient link to relevant sites which are managed by other organizations, companies, or individuals.");
            if (input_box==true)

            { 
            window.location.href=varible_value; 
            }

            else
            {
            // Output when Cancel is clicked
            alert ("You have opted not to leave Bank's website.");
            }

            }
        -->
    </script>

Answer №1

If you were looking for a solution, here is one possible way to achieve it (Check out JSFiddle):

$("a").on("click", function() {
    if($(this).attr("href").indexOf("http://") == 0) {
        return confirm("Please confirm your action");
    }
});
  • This method only handles links with http:// and not https://. It also does not verify if the link is within your current domain, but it provides a starting point for addressing the issue.

Answer №2

I struggled with implementing the confirm() function, but after exploring various Q&A's, I devised an alternative solution:

  • Opening external links in new windows and tracking outbound clicks
  • Creating a JQuery confirm dialog
  • Utilizing WordPress and jQuery UI CSS Files
  • Finding hosted jQuery UI themes online
  • Understanding why jQuery UI 1.10 removed jquery dialog zIndex option

You can incorporate the provided code snippet into your theme's functions.php file, but it is recommended to create a separate plugin for this purpose. Learn more about this approach here.

add_action( 'wp_enqueue_scripts', 'enqueue_scripts_so_22382151' );
add_action( 'wp_header', 'print_header_so_22382151' );
add_action( 'wp_footer', 'print_footer_so_22382151' );

/**
 * Enqueue jQuery Dialog and its dependencies
 * Load jQuery UI theme from Google CDN
 */
function enqueue_scripts_so_22382151() {
    wp_enqueue_script( 'jquery-ui-dialog', false, array('jquery-ui','jquery') );
    wp_enqueue_style( 'jquery-ui-cdn', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/dot-luv/jquery-ui.min.css' );
}    


/**
 * Implementing custom styles for the dialog
 */
function print_header_so_22382151() { 
    ?>
    <style>
        /* Customizing the appearance of jQuery UI dialogs */
        .ui-front {
            z-index:1000000 !important; /* Overriding the default z-index value */
        }
        .ui-widget-overlay {
            opacity: .8;
        }
    </style>
    <?php
}

/**
 * Injecting script for the dialog functionality
 */
function print_footer_so_22382151() { 
    $current_domain = $_SERVER['SERVER_NAME'];
    ?>
    <script type="text/javascript">
        jQuery(document).ready(function ($) {
          $('a[href^="http://"],a[href^="https://"]')
            .not('[href*="<?php echo $current_domain; ?>"]')
            .click(function(e) {
                e.preventDefault();
                var url = this.href;
                $('<div></div>').appendTo('body')
                    .html('<div><h6>Link Disclaimer:  [...].</h6></div>')
                    .dialog({
                        modal: true, title: 'message', zIndex: 10000, autoOpen: true,
                        width: 'auto', resizable: false,
                        buttons: {
                            Yes: function () {
                                window.open(url);
                                $(this).dialog("close");
                            },
                            No: function () {
                                $(this).dialog("close");
                            }
                        },
                        close: function (event, ui) {
                            $(this).remove();
                        }
                    });
            })
        });
    </script>
    <?php 
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for using rspec to test front end functionality?

In my Rails project, I have incorporated Vue.js using only the core library. Currently, most forms in the project are developed with Vue.js. When testing front-end features like form filling or validations using feature tests in RSpec, I found it to be qui ...

The catalog search feature is malfunctioning in Magento version 1.9.0.1

I'm looking to customize my search function to only include the product title. I have already removed the description from the catalog search in the backend, but it's still searching based on the description as well and not giving me the results ...

It is not possible to access fields in Firestore using Node.js

Exploring the limits of my Firestore database access with a test function: exports.testfunction = functions.https.onRequest(async (request, response) => { try{ const docRef = firestore.collection("Stocks").doc("Automobile" ...

Making the Select Tag function as an on-click event in JQuery

So I currently have a tab set up that functions as on click links when viewed on desktop. However, for tablet and mobile devices, I need it to be transformed into a select drop down list while maintaining the same functionality. Below is the code used for ...

Dealing with an Incorrect Date in JavaScript

After working on a JavaScript logic to extract date and time from certain values, I realized that my approach needed some adjustments. Initially, I parsed the DateTime and converted it to a string. Then, I split the string to retrieve the date component. ...

Mastering NodeJS Promises: Efficiently Handling Multiple http.get Requests

I have recently started learning about NodeJS and Promise functionality, so please be patient with me if this question seems uninformed. My goal is to first retrieve a database of records and then verify that the links associated with these records return ...

Is it possible to implement a jQuery function instead of utilizing an iframe? Iframe tends to have a longer loading time, so using a

Would it be possible to achieve the same functionality as an iframe using the onload function and trigger function in jQuery with a div or anchor tag? I'm looking for alternatives to iframes because they take too long to load. Here is the current cod ...

A guide on retrieving bytecode from a specific PDF using Angular

Can anyone help me with extracting the bytecode from a selected PDF file to save it in my database? I keep encountering an error stating that my byte is undefined. Could someone please review my code and identify what might be causing this issue? I attemp ...

What is the best way to embed two controllers within an AngularJS webpage?

Currently, I have a Web Forms ASP.NET website that I am trying to enhance by adding an AngularJS page. This page is meant to interact with my RESTful Web API to display quotes for selected securities upon button click. While the Web API calls work when dir ...

Error: The JSONP request encountered an unexpected token, causing a SyntaxError

Asking for data using AJAX: $.getJSON('https://www.cryptocompare.com/api/data/coinsnapshot/?fsym=BTC&tsym=USD&callback=?', function(result) { console.log(result); }); Encountering an error: "Uncaught SyntaxError: Unexpected token :" ...

The required keys [:id] are not included in the route matches

As a beginner in Rails, I've encountered similar issues that I can't seem to resolve. Here are my routes: resources :users do resources :items end My model setup is as follows: class Item < ActiveRecord::Base belongs_to :user end cl ...

Discovering how to navigate to a link within a web table using Cypress has been a challenge, as I keep receiving the error message stating that the element is not visible due to its CSS property being

Trying to click on the first enabled link in the 'Action' column of a web table has been proving difficult. In the example given, the first two rows do not have an enabled link, so the goal is to click on '8.5 AccountH' https://i.stack ...

Trouble with buttons in table cells

There is a problem with a button placed in a table cell that spans two rows and does not fill the second row. How can I ensure that this button fills both rows? I have attempted to adjust the height in the button's style as well as in the table cell i ...

script locate the div ID within a given text and clear its content

My string contains some dynamic HTML with a div element having an id of "time", Here's an example: myString = "<div class="class">blahblah</div><div id="time">1:44</div>" How can I generate a new string that is identical to ...

Steps for creating a "search within a specified distance" feature

Although it's not a technical issue, I'm curious if anyone knows how to create a search function for finding results within an 8-mile radius of a specific city. I want something similar to the search feature on the Autotrader website. Do online ...

When I attempt to run several promises simultaneously with Promise.All, I encounter an error

My code contains a series of promises, but they are not being executed as expected. Although the sequence is correct and functional, I have found that I need to utilize Promise.all in order for it to work properly. dataObj[0].pushScreen.map(item => { ...

Sending numerous HTML forms using a sole submit button through AJAX

On my website, I have a page named publish.php where users can input details for each image they upload. Each image has its own form, but only one form is displayed at a time in a tabbed layout when the user clicks on the corresponding thumbnail. I want to ...

I'm having trouble locating the module "script!foundation-sites/dist/foundation.min.js on Heroic."

This is the content of my webpack.config.js file: var webpack = require('webpack'); var path = require('path'); process.env.NODE_ENV = process.env.NODE_ENV || 'development'; module.exports = { entry: [ 'script!jque ...

Click event binding with getter/setter in jQuery

Is there a way to replace this timeout with a getter/ setter? I want the images in the filter gallery to be sorted based on the globalVariable value when a user clicks on a section. Currently, I am using a timeout which stops working after one click. I ha ...

The issue arises when the d3 startAngle and endAngle values are set to NaN, resulting in an

I am working with a dataset that includes the following information: { current: 5 expected: 8 gap: -3 id: 3924 name: "Forhandlingsevne" progress: "0" type: 2 } Now, I have implemented the ...