I want to write a bookmarklet that will modify any webpage so that when the JavaScript code on that page does something like document.location = 'http://site.tld'
or document.location.href = 'http://site.tld'
the page will open a new tab or window instead of changing location; same as if code was window.open('http://site.tld')
;
Can I modify the prototype somehow to achieve this goal? (I use this word carelessly because although I've read about modifying prototypes a few times, I've never actually done it.) Or is there some other way?
To take control of this behavior, press Ctrl when you click a link to stay on your current page while opening the link in a new tab in the background. Likewise, use Ctrl-Shift-click to open link in new tab and switch to it. Also, Shift-click to open a link in a new window.
The open() method opens a new browser window, or a new tab, depending on your browser settings and the parameter values.
Window Location Href The window.location.href property returns the URL of the current page.
You didn't say which browser you're using, but the only way I can think of to accomplish this is using Firefox's Object.watch
.
document.watch('location', function(prop, oldval, newval) {
window.open(newval);
return '#';
});
This will intervene on any attempt to set document.location
, open a window with the same argument instead, and then change the assignment to '#'
instead (which will do nothing, usually).
In bookmarklet form, and expanded to cover both document.location
and window.location
:
javascript:(function(){var handle=function(prop, oldval, newval){window.open(newval); return '#';};document.watch('location',handle);window.watch('location',handle);})();
But even this won't work against assignment to document.location.href
; the location object is some special thing that Object.watch
refuses to work on.
If that's not enough, you could use onbeforeunload
to prompt you when you try to navigate away and cancel it (if that's your goal here).
Best I've got, sorry!
I was going to suggest using the ES5 Object.defineProperty, but as it should be, document.location is a "configurable: false" object, meaning that it can't be changed. For the curious, if you would be able to change it the code would be like this:
Object.defineProperty(document.location, 'href', {
get: function() { return this.href },
set: function(value) { this.href = value; window.open(value); return false} //Not sure about this part, but anyways...
});
Edit: Answering your question, i don't think that this is achievable via a bookmarlet.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With