0

I prefer to never lose my Admin view. If I click on a link in the Admin and it goes to another part of the Admin (e.g. New Post), great. But if a link goes either to my site's front-end or to an external link, I'd like that to open in a new tab. I started with this:

function DB_admin_inline_js() { ?>
    <script type='text/javascript'>
        jQuery( document ).on( 'click', 'a', function( e ) {
            if ( ( this.hostname != document.location.hostname )
                ||
                ( this.href.indexOf( 'wp-admin' ) == -1 ) ) {
                window.open( this.href, '_blank' );
                return false;
            }
        });
</script>
<?php }
add_action( 'admin_print_footer_scripts', 'DB_admin_inline_js' );

That solution works well in the simple case but it falls down when links in the Admin have JavaScript attached to them, i.e. weren't meant to open a new location. So I started adding things and with some trial and error, ended up adding these two tests before that if statement:

        if ( this.target != '' && this.target != '#' ) {
            return false;
        }
        if ( this.href.startsWith( 'javascript:' ) ) {
            return true;
        }

This works much better but it's still not perfect and sometimes when I click on a link, a new tab opens that is blank - because it's not meant to open a new location. Typically when a coder has implemented something unexpected like a dropdown list using links+JavaScript instead of a true dropdown.

Can anyone suggest a more general way to solve this?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.