WordPress.org

Making WordPress.org

Changeset 10520


Ignore:
Timestamp:
12/16/2020 07:30:13 AM (13 months ago)
Author:
dd32
Message:

Theme Preview: Prevent navigation to external urls that are not WordPress.org hosted.

As these previews are used within iframes on WordPress sites we need to ensure that only sites we control can be loaded within the iframe.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • sites/trunk/wp-themes.com/public_html/wp-content/mu-plugins/pub/open-links-in-new-window.php

    r10510 r10520  
    33/**
    44 * Plugin Name: Open external links in new window/tab.
    5  * Description: Injects some JS to cause all external links to open in a new tab, to work around X-Frame-Options (and presenting something as WordPress.org that isn't).
     5 * Description: Injects some JS to WordPress.org links to open in a new tab, and prevent navigation to other hostnames breaking preview iframes.
    66 */
    77
    88add_action( 'wp_footer', function() {
    99    echo '<script>
    10 ( function( base ) {
     10( function() {
    1111    var links = document.getElementsByTagName( "a" );
    1212    for ( var i = 0; i < links.length; i++ ) {
    13         var href = links[i].href.split( "#" )[0];
    14         if ( href && base !== href.substring( 0, base.length ) ) {
    15             links[i].target = "_blank";
     13        var link = links[i],
     14            url,
     15            hostname;
     16
     17        try {
     18            url      = new URL( link.href, document.location.href );
     19            hostname = url.hostname;
     20            if ( "mailto:" === url.protocol ) {
     21                hostname = "mailto"; // not whitelisted hostname to fall through.
     22            }
     23        } catch( e ) {
     24            // Internet Explorer and invalid links, fall back to regex.
     25            if ( hostname = link.href.match( /^\s*(?:(?:https?:)?\/\/)([^/]+)(\/|$)/ ) ) {
     26                hostname = hostname[0];
     27            }
    1628        }
     29
     30        // Self links are allowed.
     31        if ( ! hostname || "wp-themes.com" === hostname ) {
     32            continue;
     33        }
     34
     35        // Links to WordPress.org should be allowed, but open in a new window.
     36        if ( "wordpress.org" === hostname || ".wordpress.org" === hostname.substr(-14) ) {
     37            link.target = "_blank";
     38            continue;
     39        }
     40
     41        // The link should not be followed, but the href is kept to allow for a[href^=] based styling.
     42        link.addEventListener( "click", function( e ) {
     43            e.preventDefault();
     44        } );
    1745    }
    18 } )( ' . wp_json_encode( home_url( '/' ) ) . ')
     46} )();
    1947</script>';
    20 } );
     48}, 9999 );
Note: See TracChangeset for help on using the changeset viewer.