Archive for the 'bookmarklets' Category

YSlow development: getting started

Sunday, June 17th, 2012

Since version 2.0, YSlow is no longer just a tool, it's a platform. You can create your own rules (performance or otherwise), combine them into rulesets, tweak scores to your liking and so on.

Once Marcel took over and did version 3.0. YSlow can now run in many many environments: as a Firebug extension (like version 1.0 did), as a Firefox extension, Chrome extension, command-line and so on... including running as a bookmarklet in any browser (including mobile browsers). Funny aside is that YSlow version 0.XYZ was originally just a bookmarklet. Now it's a bookmarklet among everything else.

Now, setting up for browser extension development can be intimidating if you've never done it. But worry not, I want to show you how you can create YSlow extensions and customizations knowing nothing but JavaScript.

We'll be using the bookmarklet version for development.

What's even lovelier is that YSlow is open source now on Github.

Stay tuned

I wish I could tell you more, but it's father's day and the backyard BBQ party (including a rare live appearance from Anaconda Limousine) starts in an hour. And something tells me I won't feel very bloggy after the party. So YSlow would have to wait.

If you cannot wait though here are some pointers:

So welcome to the exciting world of YSlow development, it's fun and games and new rules and new integrations and pure webperf joy!

 

Statsy – more data points for markup quality

Monday, November 30th, 2009

In the spirit of the content-to-markup ratio bookmarklet, here's another one that gives you some more data points to help you judge the quality of a page's markup and help answer the old question - where does all this page weight go.

Install the statsy bookmarklet

Drag this link to your bookmarks:

statsy

the results

Once you run the bookmarklet it alerts these stats points:

  • JS attributes (e.g. onclick) - this is the sum of all onclick, onmouseover and so on including the attribute names. So for example <a onclick="#"> is 11 characters (bytes) of JavaScript attributes code
  • CSS style attributes - the sum of all style="..."
  • Inline JS - the sum of all the contents of all script tags (excluding the tag itself)
  • Inline CSS - sum of all <style> tag contents
  • All innerHTML - this is document.documentElement.innerHTML.length, it should be close to the ungzipped size of a page, provided the page is not doing a lot of DOM manipulation
  • # DOM elements - the total number of elements on the page is counted simply using document.getElementsByTagName('*').length

Here's example output:
statsy bookmarklet output

The code

The code is here for your tweaking pleasure

Thanks!

Hope you'll find this bookmarklet useful when looking at a page as a companion to YSlow/PageSpeed.

What else should I add to this bookmarklet? # of font tags, # of table tags...?

 

Content-to-markup ratio bookmarklet

Thursday, March 5th, 2009

When you care about performance, or SEO (or just doing a good job as web dev) an interesting data point is the ratio of page content vs. the markup used to present this content. Or... how much crap we put in HTML in order to present what the users want to see - the content.

So I played tonight with a bookmarklet to provide this piece of stats.

Install

Right-click, add to favourites/bookmarks. Or simply click to see the ratio of this page.

content/markup

How it works

Since the scripts on the page may modify the content and markup, the bookmarklet makes an Ajax request to get a fresh copy of the page from the server. Then it runs a few regular expressions ("borrowed" from prototype.js) to strip all tags and the scripts/styles content. The first metric it provides is the size of the stripped content divided by the size of the original markup.

Then the bookmarklet tries to be more fair and count the alt, title and value attributes as content, including the size of attribute names themselves. And this is the second, "fair", metric. The content attributes are inspected using DOM methods, not regexp, so they can be affected by any javascript that has modified the page. Oh well, life's not fair.

Code

The bookmarklet code is served from here. The code is also on github.

Results

Here are some random results of running the bookmarklet on different sites.

http://www.cnn.com:

Total size: 92004 bytes
Content size: 11475 bytes
Content-to-markup ratio: 0.12
Fair ratio * : 0.16

http://www.sitepoint.com

Total size: 65989 bytes
Content size: 16199 bytes
Content-to-markup ratio: 0.25
Fair ratio * : 0.60

Article on http://en.wikipedia.org:
Total size: 21648 bytes
Content size: 3315 bytes
Content-to-markup ratio: 0.15
Fair ratio * : 0.35

http://www.phpied.com

Total size: 31899 bytes
Content size: 7933 bytes
Content-to-markup ratio: 0.25
Fair ratio * : 0.48

http://www.google.com SERP
Total size: 29963 bytes
Content size: 3351 bytes
Content-to-markup ratio: 0.11
Fair ratio * : 0.14

 

Replace the Home button with a script

Tuesday, March 3rd, 2009

Robert Ames commented on my previous post suggesting replacing the Home button with my little site search bookmarklet. I didn't even know this was possible, but I found it pretty cool, so I just had to try.

x-browser

I tried this in Firefox/Mac and IE/Windows and it works just fine.

ok, what is it?

Well, the idea is simple: when setting the homepage in your browser, instead of providing an http://... URL, you can use the javascript:... pseudo-protocol. So for example you can type:

javascript:alert(document.title)

And then every time you hit the Home button in the browser, an alert with the page title will pop up. How cool is that!

Naturally, you can replace the simple javascript with any sophisticated bookmarklet of your choosing (hint, hint)

how-to

In Firefox on the Mac you go Firefox / Preferences. On Windows: Tools / Options. Then in the Main tab, you type/paste the bookmarklet code.

Setting the Home to a javascript bookmarklet in Firefox

For IE/Windows go Tools / Internet Options and select the General tab

Internet Explorer - setting the Home button to a javascript bookmarklet

 

Search site bookmarklet with YUI and BOSS

Saturday, February 21st, 2009

Ever wanted to search only the web site you're currently on? Not the page, but the whole site. And only this site, not the rest of the web. This bookmarklet does just that.

Install

Right-click this link and add to your bookmarks/favorites. Or just drag to your bookmarks toolbar.

search site

Or if you don't want to add the bookmarklet, you can simply click the link above and try it out.

Use

You can search any site. Just visit the site and click the bookmarklet. There's also keyboard navigation to move up/down the results. The search results display as you type and the first results is highlighted so you can just press Enter and follow the first match of your query.

Here's a short video that shows how you can use the bookmarklet to search my blog.


search site bookmarklet @ Yahoo! Video

Under the hood

The bookmarklet uses YUI and BOSS to do its magic.

YUI (Yahoo User Interface) library's Dom, Event and Get utilities make a task like this so much easier.

BOSS (Build your Own Search Service) is a mildly confusing name for Yahoo Search's API second major iteration. The API allows you to specify a site (or sites) that you want to limit your search query.

The bookmarklet simply includes searchsite.js served from here; the bookmarklet was generated with the help of this bookmaker.

Show me code!

It's on GitHub, right here under the searchsite directory, it's just one script file searchsite.js, not at all documented, but I hope you'll make sense of it.

 

Short Amazon affiliate links – a bookmarklet

Sunday, October 19th, 2008

It's a pain to link to a specific product on Amazon if you have to use their UI to build an affiliate link. It's good to have nice, clean and short affiliate links. This post gives you the details and also a bookmarklet to built the links by visiting the product page you want to link to.

Anatomy of an Amazon affiliate link

Let's see the anatomy of a link in its shortest possible form.
Basically you have:

  • http://www.amazon.com/ - self-explanatory, I think
  • /dp/ - standing for "details product" or maybe "details page"
  • /1847194141/ - a 10 character product code, aka ASIN code, Amazon Standard Identification Number
  • ?tag=affiliatecode-20 - your affiliate code, or tag

For example my Amazon affiliate code is w3clubs-20, and an affiliate link to my book would be:
http://www.amazon.com/dp/1847194141/?tag=w3clubs-20

Amazon also uses longer search engine friendly URLs containing the book title, like:
http://www.amazon.com/Object-Oriented-JavaScript-Stoyan-Stefanov/dp/1847194141/?tag=w3clubs-20

But the book title/product name doesn't really matter, so this is fine too:

http://www.amazon.com/War-and-Piece-by-Stoyan-Stefanov/dp/1847194141/?tag=w3clubs-20

So I went ahead and created a bookmarklet that lets you visit the product page you want to link to, click the bookmarklet and copy a short affiliate URL.

Install the bookmarklet

Drag the link below to your favorites/bookmarks or right-click and add to favorites. Then right click the new bookmark and change its properties, replacing my Amazon affiliate code "w3clubs-20" with yours.

Amazon aff

After installing the bookmarklet, just go to any Amazon product page, click the bookmarklet and it will create an affiliate link for you to copy.

The bookmarklet code, readable version

Here's the code for the bookmarklet, simply find the ASIN (product code) and build a new URL with it.

(function(){
    var aff = 'w3clubs-20'; 
    if (!document.getElementById('ASIN')) {
        alert('Can\'t find the product ID'); 
        return;
    } 
    var asin = document.getElementById('ASIN').value;
    prompt(
        'Here is the link:',
        'http://www.amazon.com/dp/' + asin + '/?tag=' + aff);
})()

Misc

There's a page in the Amazon affiliates section that let's you check if the links are OK, it's here

Sometimes you might see (usually for non-book products) URLs that instead of /dp/ have /gp/product/, but if you build /dp/ links it's totally fine, according to their link checker, see previous paragraph.

 

Javascript console in IE

Saturday, October 18th, 2008

I'm a sucker for consoles. The ability to quickly type some code and see it executed right then and there... priceless. That's why I'm a huge fan of Firebug's JavaScript console. But what about IE?

option 1 - Firebug lite

Firebug lite is a lighter version of the proper Firebug which runs in browsers other than Firefox. You "install" the bookmarklet and voila - JavaScript console and other goodies are available on any page.

You visit any page and click the "Firebug lite" bookmarklet...
firebug lite bookmarklet

... then you hack away in the shiny console!
firebug lite bookmaklet in action

option 2 - built-in MS script editor/debugger

If you do any javascript in IE, it's a good idea to have this debugger guy enabled. There's actually at least three different debuggers, but one of them is already installed without you lifting a finger. If you enable it, you can debug any time there's a JavaScript error on the page. It also features a console! You can't get to the console unless there's a JS error, so you may need to cause the error yourself. Here's the step-by-step scenario.

Go to menu Tools / Internet Options... / Advanced tab. Under the "Browsing" category uncheck the box that says "Disable Script Debugging"
set the IE options

Go to any page and cause an error, by typing in the address bar some non-existing property or some non-existing object for example. Like javascript:alert(a.a.a)
Go to anypage and cause an error

Non-surprisingly, you get an error, but now you have the option of debugging the error:
A error and a debug option

You're given a list of debuggers, in case you've installed more debuggers from MS. Select your debugger or just hit Yes:
pick a debugger

Just say OK here...
step into procedure

Click "Break"...
Break

Finally - a console! We're in! The console is the so-called "Immediate" window, which is not displayed by default. To see it go to menu Debug / Windows / Immediate. Then just start fiddling with the page. Type anything and hit enter to see it evaluated. You also list the properties of an object by typing its name, like document.images[0] or just document.
Fiddle with document.images[0]

Once you've had your fun, stop debugging:

Enjoy the results of your hard work, a.k.a. replacing some logo with a shot of your favorite book ;)
your fav book

 

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
Update Dec 11, 2008: updated the code thanks to the comment from Nolan

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.mediaplayer.loadPlayerScript()};
 
  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.