I’m trying to create a Javascript bookmarklet, which would extract a numeric ID from an URL:
http://site-1/script-1.php?ID=12345678&other-params
and then redirect the browser to a new URL:
http://site-2/script-2.php?id=12345678
I’ve searched net for bookmarklet examples and I have 2 questions please:
1) Do I need to place my JS-code inside a void?
javascript:void(XXX);
What does void mean in this context?
2) Should I use location.href for reading the old URL and assigning a new constructed URL? I’m asking because I’ve seen many strange pieces of code, like String(location.href) etc. – like it needs some casting to String (does it?)
UPDATE: I’ve tried the following code, but nothing happens in Chrome unfortunately, when I’m on the old page and click my bookmarklet (hoping to navigate to the new page):
javascript:void (
if ( var match = location.search.match(/id=(\d+)/i) )
location = 'http://site-2/script-2.php?id=' + match[1];
)
(I’ve added line-breaks above and yes I’m trying to use a single “=”)
UPDATE 2: My 2nd try – just trying to display a new URL:
javascript:void (
var match = location.search.match(/ID=(\d+)/);
alert('http://site-2/script-2.php?id=' + match[1]);
)
but still nothing happens, when I click the bookmark at the bookmarks bar. And I see in Google Chrome console:
Uncaught SyntaxError: Unexpected token var
1) If your bookmarklet returns a value so that after all code is run, the url could be read as:
javascript:%somestring%the browser will display that string in the browser window. Sovoid()is just a safeguard (ref...The void operator evaluates the given expression and then returns undefined...) against accidently overwriding the document. This means, if you’re careful you don’t need void.2) No need to cast it, as it will happen automatically if you don’t provide a string value.
My bookmarklet template:
Update: