views:

74

answers:

2

Hi all,

I've got a nice piece of javascript

<script type="text/javascript"><!--
var d = new Date();
d.setTime(d.getTime()-86400*1000);
window.location = "https://mail.google.com/mail/?shva=1#search/in%3Ainbox+before%3A"+(d.getYear()+1900)+"%2F"+(d.getMonth()+1)+"%2F"+d.getDate();
//-->
</script>

That works entirely satisfactorily when I visit the .html file that i store the javascript in.

However, I'd like to get the same effect from using a bookmarklet - however, when I put

javascript:var%20d%20=%20new%20Date();%20d.setTime(d.getTime()-86400*1000);%20window.location%20=%20"https://mail.google.com/mail/?shva=1#search/in%3Ainbox+before%3A"+(d.getYear()+1900)+"%2F"+(d.getMonth()+1)+"%2F"+d.getDate();

into my bookmark I'm taken to re:2010/4/20 rather than re%3A2010%2F4%2F20

I'm assuming that there's some problem with the escape characters in either the bookmarking system or javascript but I'm not getting anywhere - anyone care to lend a hand?

Joe

A: 

I would try wrapping that whole chunk of code in a function, so that your bookmarklet (un-escaped) looks like this:

(function() {
    var d = new Date();
    d.setTime(d.getTime()-86400*1000);
    window.location = 
      "https://mail.google.com/mail/?shva=1#search/in%3Ainbox+before%3A" + 
      d.getFullYear()+"%2F"+(d.getMonth()+1) + "%2F" + d.getDate();
})();

But that's just me. More important, those escaped characters would need to be double-escaped when you're turning it into bookmarklet form.

javascript:%28function%28%29%20%7B%0A%20%20%20%20%20%20%20%20var%20d%20%3D%20new%20Date%28%29%3B%0A%20%20%20%20%20%20%20%20d.setTime%28d.getTime%28%29-86400*1000%29%3B%0A%20%20%20%20%20%20%20%20window.location%20%3D%20%0A%20%20%20%20%20%20%20%20%20%20%22https%3A//mail.google.com/mail/%3Fshva%3D1%23search/in%253Ainbox+before%253A%22%20+%20%0A%20%20%20%20%20%20%20%20%20%20d.getFullYear%28%29+%22%252F%22+%28d.getMonth%28%29+1%29%20+%20%22%252F%22%20+%20d.getDate%28%29%3B%0A%20%20%20%20%7D%29%28%29%3B

Also there's a function on Date instances called "getFullYear".

Pointy
Worked fine, thanks a lot :)
Joe Reddington
A: 

Why the %20 - none of my bookmarklets ever needed that

mplungjan