Upgrade to Pro

How To Make External Links Open in a Fancy Popup Frame

To make external links open in a fancy popup frame (like a lightbox or modal) in a PHP project using JavaScript, follow this

1. HTML + JavaScript (Vanilla JS + CSS Popup Frame)

  JavaScript Code

<!-- Add this in the footer of your page or just before </body> -->
<script>
document.addEventListener("DOMContentLoaded", function () {
    const currentHost = window.location.host;

    document.querySelectorAll("a[href^='http']").forEach(link => {
        const linkHost = new URL(link.href).host;
        if (linkHost !== currentHost) {
            link.addEventListener("click", function (e) {
                e.preventDefault();
                openPopup(link.href);
            });
        }
    });

    function openPopup(url) {
        const popup = document.getElementById("popup-frame");
        const iframe = document.getElementById("popup-iframe");
        iframe.src = url;
        popup.style.display = "block";
    }

    document.getElementById("popup-close").addEventListener("click", function () {
        document.getElementById("popup-frame").style.display = "none";
        document.getElementById("popup-iframe").src = "";
    });
});
</script>

CSS + HTML for Popup Frame

Add this inside your <body> HTML (can be placed anywhere but often just before </body>):

<style>
#popup-frame {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0,0,0,0.8);
    display: none;
    justify-content: center;
    align-items: center;
    z-index: 9999;
}
#popup-content {
    position: relative;
    width: 90%;
    height: 90%;
    background: white;
    border-radius: 10px;
    overflow: hidden;
}
#popup-iframe {
    width: 100%;
    height: 100%;
    border: none;
}
#popup-close {
    position: absolute;
    top: 10px;
    right: 15px;
    font-size: 20px;
    font-weight: bold;
    cursor: pointer;
    z-index: 99999;
}
</style>

<div id="popup-frame">
    <div id="popup-content">
        <span id="popup-close">✖</span>
        <iframe id="popup-iframe"></iframe>
    </div>
</div>

 Example External Link

<a href="https://example.com" target="_blank">Visit Example</a>

 Notes

  • Works in PHP projects as it's all front-end.

  • You can enhance it with libraries like SweetAlert2, Magnific Popup, or FancyBox for better design.

  • Make sure X-Frame-Options is not blocking iframe embedding on the target site.

Flowisetech For easy access