Safari – Duplicate a Tab Next to Itself

Hey Folks,

Occasionally I want to duplicate a page in Safari next to itself, and there’s no convenient built-in method.

From an Execute an AppleScript action.

# Duplicate Safari Tab next to itself.
set js to "
var docURL = document.URL;
var open_link = window.open('','_blank');
open_link.location=docURL;
"
tell application "Safari"
  tell front document
    do JavaScript js
  end tell
end tell

Or place this JavaScript in a bookmark on the Favorites Bar and access via ⌘⌥[0-9] or mouse-click.

javascript:var%20docURL%20=%20document.URL;var%20open_link%20=%20window.open('','_blank');open_link.location=docURL;

Or run the pure JavaScript code from an Execute JavaScript in Safari action.

var docURL = document.URL;
var open_link = window.open('','_blank');
open_link.location=docURL;

-Chris

One very minor thought on JavaScript style:

Because the global namespace is already so over heavily over-populated (try evaluating the keyword this even in the OS X Script Editor, let alone in a browser), I would personally tend either not to add more names to that space (where they can all too easily collide with existing names, and will persist after the code execution), or, if do need them, I would tend to declare them in a fresh local name space. i.e.

without creating persistent global variables, just:

window.open('','_blank').location=document.URL;

or creating variables, if you need or prefer them, but making them local and transient, by wrapping them in an anonymous and immediately executed function:

(function () {
  'use strict';

  var docURL = document.URL,
      open_link = window.open('', '_blank');

  open_link.location = docURL;

})();

( Inside the 'module' constituted by that anonymous function, the global name space is still visible/readable/invokable, but any variable declarations become purely local and short-lived,
while any inadvertent name collisions are locally resolved - your definition gets priority and doesn't
overwrite the page's prior use ).



To take a quick look at the default (global) namespace in the current web page, and the potential for inadvertent variable name collisions:

View global namespace in Safari page.kmmacros (18.8 KB)

(function () {
    var lstNames = Object.keys(this);

    return lstNames.length + ' names already bound in the global namespace ...' +
        '\n\n' + lstNames.join('\n');
})();
1 Like

Hey Rob,

Thanks.

And thanks for providing the proof as well; that helps on a variety of levels.

-Chris

I usually just use Command-L, Command-Enter for this.

2 Likes

Ah, that’s too easy. We NEED to program. :astonished:

1 Like

Ah, that’s too easy. We NEED to program. :astonished:

If there’s no work how can we feel we’ve accomplished something? :wink:

1 Like

Yeah, but that’s two keystrokes.   :sunglasses:

-Chris

1 Like

Which Keyboard Maestro could easily turn into one. :grinning:

1 Like