Archive for the 'bookmarklets' Category

Bookmarklet maker tool

Saturday, May 10th, 2008

Helps you easily turn any javascript code into a bookmarklet and post on your blog:
http://tools.w3clubs.com/bookmaker/

 

Google docs bookmaklet to format code

Sunday, January 27th, 2008

Something has been annoying me for some time as I write this book in Google Docs: I want to be able to format text as code (Courier New) only using the keyboard. So I came up with this bookmarklet. It's one of those "works for me" so if it doesn't work for you feel free to modify and post here your version.

Code

Basically I attach an event (FF way, so won't work in IE) that listens to the keyboard combination ALT+x and then calls the appropriate editor command:

javascript:(
function(){
  window.frames[1].document.addEventListener(
    'keypress',
    function(e){
      if (e.altKey && e.charCode === 120){
        EditorCommand('fontname', 'Courier New');
        return false;
      }
    },
    false);
}
)()

Download

Right-click, bookmark:

Alt+X

 

MP3 player from Yahoo! - bookmarklet

Wednesday, January 23rd, 2008

Update Jan 30, 2008: updated code based on comments and code from Carl

Here's the scenario: you have a page that links to some .mp3 files. You add a line of code in your page and lo and behold, there's a nice media player embedded into the page. Your visitors no longer have to download the MP3s, they can just stream it right there. All the mp3s on the page become part of a playlist.

The line in question you need to add to your page is:

<script src = "http://mediaplayer.yahoo.com/js"></script>

More about the player here - yahoomediaplayer.wikia.com

For examples of sites using this player in the wild, try aurgasm.us

A bookmarklet

Now, here's what you can do if you want to use the player, but the web site owner haven't incorporated it yet. Take the player with you. Run my bookmarklet that will simply insert the required javascript into the page.

So here goes in two easy steps:

  1. Grab the bookmarklet:

    Right-click, add to favorites

  2. Go to any page that links to MP3s and click your new shiny bookmarklet

    Enjoy!

Source

The readable source code of the bookmarklet:

javascript:(function(){

  var start = function(){YAHOO.music.WebPlayer.asyncLoadPlayer()};

  var script = document.createElement('script');
  script.src = 'http://mediaplayer.yahoo.com/js';

  if(script.addEventListener){
    script.addEventListener("load", start, false);
  } else{
    script.onreadystatechange = function(){
      if(this.readyState=="complete"){
        start();
        script = null;
      }
    }
  }
  script.type="text/javascript";
  document.getElementsByTagName('head')[0].appendChild(script);

})();
 

Netflix - how many movies you've rented

Sunday, December 30th, 2007

Netflix is a great service, it's a shame they don't seem to provide any APIs. Oh, well, we'll have to resort to other means of extracting data.

A little javascript to count how many movies you've rented:

document
    .getElementById('returned_movies')
    .getElementsByTagName('tbody')[0]
    .getElementsByTagName('tr')
    .length

You can put this code in a bookmarklet or simply type in the Firebug console.

As people say "your markup is your API".

 

"Save AnyThing" offline with a Google Gears bookmarklet

Friday, October 19th, 2007

Here's a little bookmarklet I came up with, I called "SAT", stands for "Save AnyThing (for offline reading)". It uses Google Gears and works like this:

  • you're about to go offline (maybe boarding a plane) and want to catch up on some reading
  • you visit any page
  • you click the SAT bookmaklet
  • it saves all the pages that are linked from the current page (only those on the same domain, you know, security and stuff)
  • you disconnect from the Net and read offline

Pretty cool, eh?

Initially I wanted to experiment with Google Gears and write a phpBB extension to save the latest forum topics for offline reading. But after thinking about it a bit I thought it can be done in an even more generic way and save anything for offline reading. All you need is a page that has a bunch of links, any page - a forum, a blog, the array section of the PHP manual… anything. After you run the bookmaklet, you'll have an offline copy of all the linked pages. Gotta love those bookmarklets, nothing to install, just a click in the favourites.

Demo

satdemo.png

» Click here for a recorded demo

(demo is kinda clumsy, my first attempt in screen recording, I used Adobe Captivate, pretty bad I couldn't upload the result to youtube)

For a live demo, you can also test the bookmarklet by simply clicking the download links below.

Download

Drag those two links to your favorites/bookmarklets. The first one is to store offline pages, the second is to remove the stored versions.

Source code

If you want to take a peek at the source code, the human-friendly versions are here:

Note on pages that will not be stored offline

Not all pages will be stored offline. I'm aware of these reasons why (there might be others)

  • same-origin security policy
  • Gears won't follow redirects

Comments, bugs

Thanks for reading, any comments are appreciated. My guess is the bug count will be pretty low, due to the fact that when the sh…, er, the bug hits the fan, you'll be offline and cannot report it :)

Now that I'm all set with stuff for offline reading for my short LAX-SJC flight tomorrow, I cannot help but wonder - should I still take with me a plain old reliable hardcopy of a piece of pulp fiction? You know… software breaks :)

 

YUI anywhere (bookmarklet)

Friday, June 8th, 2007

Hooked on YUI? You can now take it anywhere you go. The thing is Yahoo hosts the libraries publicly, so they are available at any time. Let's say you visit a page and you want to do something with it. Comes the YUI bookmaklet that adds a new script tag to the page pointing to utilities.js that contains all YUI utilities (DOM, Event, DragDrop, Animation, Connection…). Then just open your Firebug console and start messing with the page. The powerful toolset that YUI is, is at your disposal.

The code

The code for the bookmarklet is really simple, just a question of adding a new script tag.

(function(){
    var s = document.createElement('script');
    s.src='http://yui.yahooapis.com/2.2.2/build/utilities/utilities.js';
    document.getElementsByTagName('head')[0].appendChild(s);
})()

Install

Right-click, add to favorites, or drag to bookmarks.

YUI anywhere

Let the fun begin

So you go to any page, click the bookmarklet and for example decide to make the logo on the page draggable. All you need to write in your JS console (or in address bar for IE) is:

new YAHOO.util.DD('logo')

The result is really not bad for a one-liner. But why stop there? Let's make everything on a page draggable.

var all = document.getElementsByTagName('*');for(var i = 0; i < all.length; i++) {new YAHOO.util.DD(all[i])}

Whoa! We can mess up with other people's pages like we've never messed up with other people's pages before! Example:

google-yui-drag.png

And why only other people's pages, what about ours? Imagine you're sitting with a client or boss, showing the new site and they go:
- Hmm, well, you know, I don't know about this spacing between the images here …
And you:
- Hold that thought (clicking bookmarklet, making everything draggable, dragging the offending image). Is this how you prefer it?
Client:
- Well, maybe, or actually it was better before.
You:
- Ah, OK, whatever suits your business needs

Update: Some more one-liners to prevent loading a new page when you attempt to drag a link or a submit button.

Disable links:
YAHOO.util.Event.addListener(window, 'click', function(e){ if (e.target.nodeName.toUpperCase() == 'A'){ YAHOO.util.Event.preventDefault(e) } });

Prompt before unload:
YAHOO.util.Event.addListener(window,'beforeunload',function(e){ e.returnValue = "Sure?" });

 

Two bookmarklets for debugging in IE

Tuesday, February 20th, 2007

Here are two bookmarklets that could make your life easier when trying to figure out why in IE a page behave as wrong as it behaves. For Firefox we have Firebug, so none of this is necessary. For IE we have also Firebug lite (see my post), but you need some setup before you can use it. With this thing here you can mess up any page you see on the web, not only yours :)

Bookmarklet 1 - Eval() textarea

I saw this bookmarklet here and it's beautiful. When you start it, it puts a textarea at the bottom of your page and you can type javascript in it, then eval()-uate it. Perfect! Only … it doesn't work in frames. So I did the same thing but when you have frames (works without frames as well). The way mine works is - you first select some text in a frame, then you click the bookmarklet. A new textarea, ready to execute javascript will be placed in this frame (or iframe) that you selected. Also in this case when you type document.something, it refers to the document in the frame, not the frameset.
If you don't select any text and click the bookmarklet, it will place the textarea in the topmost document, so it will work for frame-free pages as well.

So here's the bookmarklet.

textarea eval

And here's a page where you can test.

Bookmarklet 2 - dump anything

After having my beautiful textarea, I wanted to be able to dump variables, like print_r() or var_dump() but for Javascript. I googled and I found this little script. All I did then is to make it a bookmarklet. How it works? You select the bookmarklet, it gives you a prompt, where you type whatever you want to dump, like document.location for example. Then it shows you an alert with all properties of this thing you typed. (Don't try to dump document though, or something else that recurses, because the script won't handle the recursion and will freeze).

Install it from here:

dump var

While this second bookmarklet will most likely work in FF as well, you don't need it, you have firebug!

 

Check/toggle 'em all

Saturday, February 10th, 2007

Recently I decided to clean up all the spam from an abandoned phpBB forum of mine, there was a lot to delete. In the phpBB version that I use there is no option to "check all" topics you want to moderate. So I came up with a little bookmarklet to do this for me. Here it is, only improved to work within frames and toggle (check if not checked, uncheck otherwise) all checkboxes in sight. Tested in FF and IE6/7.

To install, add this to your bookmarks/favourites:

Toggle 'em all

Here are
some checkboxes for your testing pleasure.

The reading friendly code:

javascript:(function(){
function checkFrames(w) {

  try {
    var inputs = w.document.getElementsByTagName('input');
    for (var i = 0; i < inputs.length; i++) {
      if (inputs[i].type && inputs[i].type == 'checkbox'){
        inputs[i].checked = !inputs[i].checked;
      }
    }
  } catch (e){}
  if(w.frames && w.frames.length>0){

    for(var i = 0; i < w.frames.length;i++){
      var fr = w.frames[i];
      checkFrames(fr);
    }
  }
}
checkFrames(window);
})()
 

User stylesheet in IE

Saturday, January 20th, 2007

Let's say you want to quickly try out some small stylesheet changes, but you don't want to (or prefer not to, or for some reason temporarily you just can't) modify your application's CSS file(s). In FF it's easy - you have Firebug and you can play with styles until blue in the face. And in case you do get blue in the face and start making so many changes that you get lost, you can create a new clean and tidy CSS file, place it on your hard drive and use Web Developer extension to load it (Menu CSS->Add User Style Sheet). With WebDev Extension you can also Edit CSS right there, although unfortunatelly it's not always working when you have frames.

OK, there are options for Firefox. But how about IE?

In IE you have IE Developer Toolbar, definitelly helpful, but you can only modify element styles, not the stylesheet rules. So? A tiny little bookmarklet to the rescue!

My bookmarklet assumes you have a file called C:\user.css and loads this stylesheet on demand in your page, in every frame, just in case you use frames. Simple, yet useful, I hope. Here's the (readable) code:

javascript:
var css_file = prompt('Which CSS file you want to load today?','c:/user.css');
function addcss(w) {
    var html_doc = w.document.getElementsByTagName('head')[0];
    var css = w.document.createElement('link');
    css.setAttribute('rel', 'stylesheet');
    css.setAttribute('type', 'text/css');
    css.setAttribute('href', css_file);
    html_doc.appendChild(css);
}
var errors = 0;
function checkFrames(w) {
  if(w.frames && w.frames.length>0){
    for(var i=0;i<w.frames.length;i++){
      var fr=w.frames[i];
      try {
        addcss(fr);
      } catch (e) {
        errors++;
      }
      checkFrames(fr);
    }
  }
}
checkFrames(window);
addcss(window);
if (errors > 0) {
    alert('Could not access ' + errors + ' frame(s)');
}

To install and play around

Right-click this link and add it to your favourites:

Add User StyleSheet

Have in mind that this is IE-only (tested IE7). I don't think FF will allow you to access files on your local drive like this. But for FF you have the tools to do this anyway.

Another option to load local stylesheets in IE is to use the user CSS capability built in the browser, you can find it under Tools/Internet Options/Accessibility, but this will load your user CSS first (as opposed to last as the case is with my bookmarklet), so the "real" style definitions will overwrite yours, unless you always use !important and the "real" styles don't.

Thanks!

Have fun with the custom CSS and let me know how you find it.

 

Firebug console for IE

Wednesday, December 6th, 2006

Update: A better version of what I was trying to do is here. It works around the cross-domain permission problems in IE by not loading a page in the frame, but putting there the actual content.

Firebug - no words to describe how cool it is, really. After the recent new release (1.0. beta) the number of features is overwhelming. I for one can't live anymore without it, seriously.

One of the things I noticed on the website is the ability to use the Firebug console in other browsers than Firefox. I don't know if this existed before version 1.0 but if it did, it was the best kept secret. I am so addicted to the console in Firefox, I use it all the time to tweak a few things here and there when I'm working on a page. Recently I was looking for something similar for IE, but couldn't find it. Lo and behold, it was right under my nose.

So, here's the page that describes how to use Firebug in IE (and others). Basically you unzip the Firebug Lite files somewhere on your server and then you include firebug.js in your pages. But why stop there? And isn't it possible to avoid including this script on every page (and forgetting to remove once you're done, or removing it prematurelly since a page, just like a painting, is never really finished). Bookmarklets to the rescue!

I wanted to host the Firebug files on my hard-drive and then use a javascript dynamic include to load firebug.js via a bookmarklet. This way I would be able to load the firebug console every time I want it, on any page. Unfortunatelly IE's security policy won't allow it. Then?

Solution

The solution I came up with is:

  1. you copy the Firebug Lite files somewhere on your server
  2. you call a bookmarklet that will load firebug.js
  3. you hit F12 and you have a console!

This procedure has to be repeated for every domain you're working on, because of the security policy that won't allow cross-domain frame scripting. You can have one copy for your http://localhost and one for every domain. To ease the creation of bookmarklets that load firebug.js, I came up with a Firebug bookmarklet generator.

In action

  1. I copied Firebug Lite files (get the .zip) on this server (phpied.com), they are here.
  2. I (and you can try the same) generate a bookmarklet, using the bookmarklet tool
  3. Add the generated bookmarklet to the favorites
  4. Go to any page on phpied.com
  5. Click the new favorite
  6. Hit F12 to show/hide the console

Here's how (a readable version of) the generated code looks like:

javascript:(function(){
  var firebug_js = document.createElement('script');
  firebug_js.setAttribute('type', 'text/javascript');
  firebug_js.src = 'http%3A//www.phpied.com/files/firebug/firebug.js';
  document.getElementsByTagName('head')[0].appendChild(firebug_js);
  firebug_js.onreadystatechange = function () {
    if (firebug_js.readyState == 'complete') {
      console.open()
    }
  }
})()

Minor improvement to the console

The Firebug Lite console executes the code you type, but doesn't show it again when you use the up/down arrows, the way it does in Firefox. So I added this feature (copying from myself), you can replace the firebug.js you download with my version.

Not sold yet?

Here's a screenshot of the console in action, I used it to change my photo on the homepage.

firebug-ie-console.png

Go ahead, please

I strongly encourage everyone to try this out. Firebug is a beautiful thing and using even a bit of it in IE is great.

 

quirks or no quirks bookmarklet

Wednesday, September 20th, 2006

Here's a bookmarklet that will tell you whether or not the browser renders your page in Standards Complaiance Mode or Quirks Mode. The bookmarklet will figure this out for the page as well as for all the frames (and their frames) recursively. Enjoy!

Install

Drag this to your bookmarklets/favorites or right click and add to favorites:

quirks or !quirks

Sample output

Here's a sample output, produced when used in my Wordpress backend when writing this post:
quirks.png

As you can see the page has two frames (probably iframes, doesn't matter), one of them is rendered in Standards Compliant Mode (CSS1Compat) the other one is in Quirks Mode (BackCompat). The overall document is CSS1Compat as well. For the frames, if they were named, you would see the name of the frame before the URL brackets.

And this is GMail, wow, lotsa frames, none compliant ;)
quircks-gmail.png

The code

The code is pretty simple, just accessing the compatMode of the the document object. Here it is in more human readable form (not one long line like bookmarket code).

var response = 'Document mode: ' + document.compatMode;
function checkFrames(w) {
  if(w.frames && w.frames.length>0){
    response+='\n\n';
    for(var i=0;i<w.frames.length;i++){
      var fr=w.frames[i];
      try {
        response+=fr.name +
              ' ('+fr.document.location+') - '+
              fr.document.compatMode+'\n';
      } catch (e) {
        response+='Could not access this frame\n';
      }
      checkFrames(fr);
    }
  }
}
checkFrames(window);
alert(response);
 

Form auto-fill bookmarklet

Tuesday, May 16th, 2006

Intro

So here's the thing, we all know we hate forms, the only thing we hate more than forms themselves is actually filling out forms. But the forms are the interface to our web apps, so we cannot do without them. What we would love to do without, but can't, is skip the application testing part where you fill out forms like there's no tomorrow, just to make sure your app is rock solid.

And filling out forms is a pain. So for some time I wanted to get my hands on a little something that can fill out a form, any form, with a click of a button. JavaScript is ideal for such a task and the best sort of a "little something" is probably a bookmarklet. That is how this bookmark was born.

What is it, what it does?

This is a bookmarklet. You go to page that has one or more forms and you click the bookmarklet. It completes the form for you with some random data. The whole thinking was to have a form ready to be submitted and generating as less validation errors as possible. Here are some details:

  • All defaults are kept as they are
  • All passwords fields are completed with the same password, in case there is a password/password confirmation combo. The default password is "secret"
  • If a text field has the string "email" in its name, the auto-generated value would be a random string @ example.org
  • If a text field has the string "name" in its name, a name-looking value will be generated.
  • All checkboxes will be checked (who knows which one of them might be "Accept terms" or anything else that is required)
  • Multi-selects will have a random number of random options selected

Install

Right-click and bookmark or drag to your personal bookmarks toolbar.

Form auto-fill

Demo

Here's the demo.

The code

The demo and the code below are "normal" code, with proper indentation and all. The actual bookmark though has to be on one line and as small as possible, so it's pretty much unreadable. Ah, and while the demo will work in IE, the bookmarklet won't, because it's too big for IE. IE allows up to about 500 characters in the URL (or a bookmarklet) while mine is about 2000 "compressed" or 3000 cleaner. So unless I do something heroic in compressing the script, it won't work on IE. No biggie I'd say, since you'll be testing your application and most likely you use Firefox anyway.

The big picture

Using JSON, the class/object is called auto and it has the following interface:

var auto ={

    // a list of names that will be used to generate 
    // normal looking names
    names: "Steve Buscemi Catherine Keener …",

    // this is where all the random words will come from
    blurb: "phpBB is a free…",

    // default password to be used in all password fields
    password: "secret",

    // the main function that does all
    fillerup: function() {},

    // helper function, returns randomly selected words
    // coming from this.blurb
    getRandomString: function (how_many_words) {},

    // helper function, returns randomly selected names
    // coming from this.names
    getRandomName: function () {},

    // returns this.password
    getPassword: function () {},

    // returns a random int from 0 to count
    getRand: function (count) {}
}

The actual form fill-out is initiated by calling auto.fillerup()

As you can probably guess, the only interesting function is fillerup(), so let me show you what it does.

fillerup()

In case you're wondering, the name of the function comes from a Sting song:
Fill'er up, son, unleaded.
I need a full tank of gas where I'm headed …

The function starts by identifying all the elements candidate to be completed:

var all_inputs    = document.getElementsByTagName('input');
var all_selects   = document.getElementsByTagName('select');
var all_textareas = document.getElementsByTagName('textarea');

OK, we have our work cut out for us, let's start by looping through the selects:

// selects
for (var i = 0, max = all_selects.length; i < max; i++) {
    var sel = all_selects[i]; // current element
    if (sel.selectedIndex != -1
        && sel.options[sel.selectedIndex].value) {
        continue; // has a default value, skip it
    }
    var howmany = 1; // how many options we'll select
    if (sel.type == 'select-multiple') { // multiple selects
        // random number of options will be selected
        var howmany = 1 + this.getRand(sel.options.length - 1);
    }
    for (var j = 0; j < howmany; j++) {
        var index = this.getRand(sel.options.length - 1);
        sel.options[index].selected = 'selected';
        // @todo - Check if the selected index actually 
        //         has a value otherwise try again
    }
}

Then - textareas, they cannot be simpler. We only check if there isn't already a value and if there's none, we get two "paragraphs" of 10 words each.

// textareas
for (var i = 0, max = all_textareas.length; i < max; i++) {
    var ta = all_textareas[i];
    if (!ta.value) {
        ta.value = this.getRandomString(10)
                   + '\n\n'
                   + this.getRandomString(10);
    }
}

Next (and last), come the inputs. They are a bit more complicated as there are too many of them. Here's the overall code with the skipped details for each input type.

// inputs
for (var i = 0, max = all_inputs.length; i < max; i++) {
    var inp = all_inputs[i];
    var type = inp.getAttribute('type');
    if (!type) {
        type = 'text'; // default is 'text''
    }
    if (type == 'checkbox') {}
    if (type == 'radio') {}
    if (type == 'password') {}
    if (type == 'text') {}
}

We're absolutely unforgiving when it comes to checkboxes - just check them all, no questions asked, take no prisoners.

if (type == 'checkbox') {
    // check'em all
    // who knows which ones are required
    inp.setAttribute('checked', 'checked');
    /* … ooor random check-off
    if (!inp.getAttribute('checked')) {
        if (Math.round(Math.random())) { // 0 or 1
            inp.setAttribute('checked', 'checked');
        }
    }
    */
}

Next, do the radios. They are a bit more complicated, because once we have an element, before checking it, we need to verify that there are no other radios with the same name (and in the same form) are already selected and checked.

if (type == 'radio') {

    var to_update = true;
    // we assume this radio needs to be checked
    // but in any event we'll check first

    var name = inp.name;
    var input_array = inp.form.elements[inp.name];
    for (var j = 0; j < input_array.length; j++) {
        if (input_array[j].checked) {
            // match! already has a value
            to_update = false;
            continue;
        }
    }

    if (to_update) {
        // ok, ok, checking the radio
        // only … randomly
        var index = this.getRand(input_array.length - 1);
        input_array[index].setAttribute('checked', 'checked');
    }
}

Passwords - trivial, just make sure you always set the same password.

if (type == 'password') {
    if (!inp.value) {
        inp.value = this.getPassword();
    }
}

And finally - the text inputs. We try to guess the nature of the text field by its name. Here there's plenty of room for improvement and more guesses.

if (type == 'text') {
    if (!inp.value) {
        // try to be smart about some stuff
        // like email and name
        if (inp.name.indexOf('name') != -1) { // name
            inp.value = this.getRandomName() + ' ' + this.getRandomName();
        } else if (inp.name.indexOf('email') != -1) { // email address
            inp.value = this.getRandomString(1) + '@example.org';
        } else {
            inp.value = this.getRandomString(1);
        }
    }
}

C'est tout

That's it, hope you liked it and start using it ;) Any comment or suggestions - let me know.