I’m Surprised Nobody’s Complained :-)

(Originally posted 2014-12-31.)

It’s a little surprising to me that nobody complained about one aspect of the behaviour in the code in GreaseMonkey Script To Sum Selected Numbers In A Web Page. I’ve been muttering under my breath and I wrote the code. 🙂

This code naively assumes that in every web page there is just one body element. It is rather naive, and I’ve known that for a long time.

What really surprised me was quite how prevalent multiple body elements are in a page. Yes, I expect that in frames; no I don’t expect too many other cases.

So, I’ve been noticing lots of pages where the little “Sum Up” button showed up in places I didn’t expect it; It seems people embed body elements in all sorts of strange places.

The fix is really very simple. I’ll show you it and then I’ll explain it.

So replace the lines

    // @version     0.0
    // ==/UserScript==

with

    // @version     0.1
    // ==/UserScript==

    // Only add to topmost window in the tab
    if(window.top!=window.self) return

and now the script will only add the button at the top of the page / tab.

So the magic here is in knowing window.top is the top-most window in a web page. The script is loaded in every window – but this new line says "do nothing for every window that isn’t the topmost window.

Now, what’s (only slightly) surprising is that nobody’s complained. It probably means only one thing: Very few people have installed the script.

But I have – and I’m benefiting from it. So I’m still ahead.

And with that I’ll wish you all a Happy New Year! (Conscious as I am that for some the new year starts at a different time but deeming it much less controversial than “Merry Christmas”. If you wish me a Happy or Merry anything I’ll probably say “thank you very much and the same to you”. “War On Christmas” my eye!)

Published by Martin Packer

.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: