How to force all non-Admin links in the Admin console to open in a new tab?

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. 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’m interacting with UI, a new tab opens. 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?

Read more here:: How to force all non-Admin links in the Admin console to open in a new tab?

Leave a Reply

Your email address will not be published. Required fields are marked *