views:

126

answers:

1

Is it possible to write a Greasemonkey script to trigger the Ctrl+A (select all) action in Firefox? (after a new page is loaded if the script is enabled???)

Help me at any level possible for you.

Update:

"Firefox has got addons to speed read or read aloud selected text. I just wish to automate the part where text is to be selected."

+3  A: 
var r = document.createRange()
r.selectNode(document.body)
window.getSelection().addRange(r)

I tried creating a new Greasemonkey script, typing the above code (which I grabbed and edited from this page), and loading a page.

It did select all the text, but for some pages, it becomes unselected immediately. For example, Google's homepage, because the page focuses the search field.


Update by BA:

This didn't work on Google because it's fighting native scripts. But, by re-running the code at onload and again after, we can preserve the selection.

Also, if the native script sets focus to an input or textarea, we must fight that.

So, a Greasemonkey script that incorporates all these ideas, and seems to work is:

//--- Save this as "SelectWholePage.user.js" and install with Greasemonkey.
//
// ==UserScript==
// @name            Select a whole page
// @namespace       google.com
// @description     Selects a whole page (equivalent to 'Ctrl-A').
// @include         http://www.google.com/*
// ==/UserScript==
//

/*--- Run the main function 3 times (when DOM ready, at load and just after
    load) because page javascript will often reset the focus and selection.
*/
LocalMain ();
window.addEventListener
(
    "load",
    function(evt)
    {
        LocalMain ();
        window.setTimeout (LocalMain, 222);
    },
    false
);

function LocalMain ()
{
    var WholePage       = document.createRange ();
    WholePage.selectNode (document.body);

    window.getSelection ().addRange (WholePage);

    var aInputs         = document.getElementsByTagName ("input");

    for (var J = aInputs.length-1;  J>0;  J--)
        aInputs[J].blur ();

    document.body.focus ();
}
KeJi
@KeJi: Good workaround idea. Rather than taking your idea and making my own answer, I added the improvements to your answer -- so you get the credit. You can rollback the edits if you don't like it.
Brock Adams
@Brock Adams: Thanks! Actually, I wanted to add something like this, but decided against it since I didn't want to use setTimeout. But I suppose it's best to give all ideas, right?
KeJi
@KeJi: Yes, and `setTimeout()` seems to be the logical way to overcome websites that change focus and/or selection when the `load` event fires.
Brock Adams