2

Trying to create a bookmarklet that asks/prompts the user for a URL parameter and outputs the value of the specified URL parameter as an alert message.

For example, given a URL, if you passes in name, the bookmarklet should output “Taylor”. If one passes in accountID, it should output “123456789”, and if email is passed then “tay@tc.com” should be outputted.

Example:

http://www.google.com/name=Taylor&accountID=123456789&email=jdoe@tc.com

Rules:

  1. This should work for ANY URL.
  2. It should use the current URL that the user is on.
  3. It should notify the user if there aren’t any URL parameters before asking/prompting the user for a parameter.
  4. Only xxxxx.js code.

Not sure how to even start this. Should I start by trying to build a search function or something like this:

(function (url, options) {
    window.open(
        encodeURIComponent(url),
        options
    );
}('http://www.google.com/name=Taylor&accountID=123456789&email=jdoe@tc.com','name, accountID, email'));
Etep
  • 2,721
  • 4
  • 17
  • 28
  • 1
    This might be helpful. http://stackoverflow.com/questions/5448545/how-to-retrieve-get-parameters-from-javascript – Domino Aug 29 '16 at 03:01

1 Answers1

0

There are many bookmarklet creators out there. It’s only a Google search away.

( function() {
    var i, param, pair,
        urlParams = window.location.search.substring( 1 ),
        atts      = urlParams.split( '&' );
    if ( atts[0] !== '' ) {
        param = prompt( 'Enter desired URL parameter:' );
        for ( i = 0; i < atts.length; i++ ) {
            pair = atts[ i ].split( '=' );
            if ( pair[0] === param ) {
                alert( pair[1] );
                return false;
            }
        }
        alert( 'URL parameter "' + param + '" does not exist.' );
    } else {
        alert( 'This URL does not contain any URL parameters.' );
    }
    return false;
} )();

Bookmarklet code:

javascript:(function()%7B(%20function()%20%7Bvar%20i%2C%20param%2C%20pair%2CurlParams%20%3D%20window.location.search.substring(%201%20)%2Catts%20%20%20%20%20%20%3D%20urlParams.split(%20'%26'%20)%3Bif%20(%20atts%5B0%5D%20!%3D%3D%20''%20)%20%7Bparam%20%3D%20prompt(%20'Enter%20desired%20URL%20parameter%3A'%20)%3Bfor%20(%20i%20%3D%200%3B%20i%20%3C%20atts.length%3B%20i%2B%2B%20)%20%7Bpair%20%3D%20atts%5B%20i%20%5D.split(%20'%3D'%20)%3Bif%20(%20pair%5B0%5D%20%3D%3D%3D%20param%20)%20%7Balert(%20pair%5B1%5D%20)%3Breturn%20false%3B%7D%7Dalert(%20'URL%20parameter%20%22'%20%2B%20param%20%2B%20'%22%20does%20not%20exist.'%20)%3B%7D%20else%20%7Balert(%20'This%20URL%20does%20not%20contain%20any%20URL%20parameters.'%20)%3B%7Dreturn%20false%3B%7D%20)()%7D)()

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Ankur Singh
  • 99
  • 1
  • 2