javascriptgoogle-chromedom-eventsuserscriptsgoogle-reader

Triggering Google-Reader's refresh in Chrome (Works in Firefox)?


I have a userscript for Google Reader, and as part of that userscript I need to trigger a refresh, which I do in Firefox by simulating a keypress for the letter r.

function simulateRefresh()
{
    var e = document.createEvent('KeyboardEvent');
    e.initKeyEvent('keypress', true, true, window, false, false, false, false, 82, 82);
    document.body.dispatchEvent(e);
}

This works in Firefox, but not in Chrome. Apparently initKeyEvent is not supported, and I'm supposed to use initKeyboardEvent.
So far I've had zero luck with this (There is no error in the console, but the refresh does not fire.) I am using jQuery if that matters.

I also tried triggering click on the refresh button, but this failed in both browsers (not sure why, the click event is firing according to the Chrome debugger, but the code is obfuscated, so I can't figure it out).


Solution

  • Google webapps often do not use a simple keypress or click, when a complex sequence of states will do. ;-)

    So sending a "click" to the refresh button does not work, but sending an "over, down, up" triad does. Like so:

    var refreshBtn = document.querySelector ('#viewer-refresh');
    
    //--- Click by itself does not work!
    triggerMouseEvent (refreshBtn, 'mouseover');
    triggerMouseEvent (refreshBtn, 'mousedown');
    triggerMouseEvent (refreshBtn, 'mouseup');
    
    function triggerMouseEvent (node, eventType) {
        var clickEvent = document.createEvent('MouseEvents');
        clickEvent.initEvent (eventType, true, true);
        node.dispatchEvent (clickEvent);
    }
    


    A similar kind of state-sequence may be required for the keyboard shortcut. (Testing continues.)

    Update: For the keyboard events, see this answer which mentions Webkit Bug 16735: "Keyboard events created with DOM have keyCode and charCode of 0" -- which is still open after 4.5 years(!!) and might apply here.