Younes
Younes

Reputation: 1

Making a script bookmarklet

Im trying to make script bookmarklet that autofills a form into a website, the script that I made based on google search worked after some modification but it works only in the console.

$($0 || 'body').find('input, textarea, select').filter(':visible').each(function(){

if( $(this).attr('id')==='email' || $(this).attr('name')==='email' )
    return $(this).val('[email protected]');

if( $(this).attr('id')==='phone' || $(this).attr('name')==='phone' )
    return $(this).val('PHONE NUMBER');

if( $(this).attr('id')==='juridiction' || $(this).attr('name')==='juridiction' )
    return $(this).val('JURIDICTION');            });

Can someone explain to me it should be done.

Upvotes: 0

Views: 63

Answers (1)

sheng
sheng

Reputation: 1372

You can use the encodeURIComponent function in JavaScript to properly encode any function. There are also websites to do this. To make a bookmarklet, you'd just prepend javascript: to your encoded script.

Simple example:

  1. Your function: alert('hello!');
  2. ...encoded alert('hello!')%3B
  3. ...now a URL: javascript:alert('hello!')%3B

(Note that step 2 was generated by running encodeURIComponent("alert('hello!');") in the browser console.)

Try it yourself by pasting the last step directly into the address bar of your browser. (You may have to retype javascript:, browsers seem to trim that off when you perform a paste, probably as a security measure.)

If you follow the exact same steps on the code snippet you provided, you should get the following:

javascript:%24(%240%20%7C%7C%20'body').find('input%2C%20textarea%2C%20select').filter('%3Avisible').each(function()%7B%0A%0Aif(%20%24(this).attr('id')%3D%3D%3D'email'%20%7C%7C%20%24(this).attr('name')%3D%3D%3D'email'%20)%0A%20%20%20%20return%20%24(this).val('some%40email.com')%3B%0A%0Aif(%20%24(this).attr('id')%3D%3D%3D'phone'%20%7C%7C%20%24(this).attr('name')%3D%3D%3D'phone'%20)%0A%20%20%20%20return%20%24(this).val('PHONE%20NUMBER')%3B%0A%0Aif(%20%24(this).attr('id')%3D%3D%3D'juridiction'%20%7C%7C%20%24(this).attr('name')%3D%3D%3D'juridiction'%20)%0A%20%20%20%20return%20%24(this).val('JURIDICTION')%3B%20%20%20%20%20%20%20%20%20%20%20%20%7D)%3B

You can now create a new bookmark and paste in that URL. Voila! A bookmarklet. Any errors will be logged in your browser console.

EDIT

Bonus tip: to easily encode multiline functions in the console, use a relatively new feature (since ES6) called template strings. Example:

encodeURIComponent(`
  alert('Line 1!');
  alert('Line 2!');
`);

This wouldn't be possible with your typical quotes.

Upvotes: 1

Related Questions