Search code examples
javascriptbookmarklet

Javascript Bookmarklet: Encoded URI


I have a piece of code which should open a website.

javascript:(function(){var google = function(){window.location='http://google.de?q=%3D%3D'};google()}())

When pasting the code to the console (Chrome) the website is opened and the URI is correctly encoded.

Using the exact same code in a JS bookmarklet, it opens the website but with the decoded URI which causes my target page to fail.

Is there anything I can do to make the bookmarklet work?

PS: In the example I use the already encoded URI, placing encodeURI or encodeURIComponent into the bookmarklet didn't help.


Solution

  • Special characters in a URL are decoded when the URL is parsed.

    A bookmarklet is a URL.

    So when the bookmarklet is parsed, the special characters are decoded.

    This happens before the URL inside the bookmarklet is parsed, so they are already decoded when it is parsed.

    In short: You have a URL inside another URL. You need to encode the special characters twice.

    javascript:(function()%7Bvar%20google%20%3D%20function()%7Bwindow.location%3D'http%3A%2F%2Fgoogle.de%3Fq%3D%253D%253D'%7D%3Bgoogle()%7D())