سؤال

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).

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

Tried $('#refreshButton').trigger('click'); ?

Your solution is to check whether the initKeyboardEvent method is implemented or not.

var e = document.createEvent('KeyboardEvents');
(e.initKeyboardEvent || e.initKeyEvent).call(e, 'keypress', true, true, window, false, false, false, false, 82, 82);
document.body.dispatchEvent(e);

This works for me in Chrome.

I think you are trying to dispatch the event from your content script, unfortunately that does not work. You need to inject the code into the page:

function injectJavaScript(textContent) {
  var scriptElement = document.createElement('script');
  scriptElement.textContent = textContent;

  (document.getElementsByTagName('head')[0] || document.body || document.documentElement).appendChild(scriptElement);
}

var code = '(' + function() {
  var e = document.createEvent('KeyboardEvents');
  e.initKeyboardEvent('keypress', true, true, window, false, false, false, false, 82, 82);
  document.body.dispatchEvent(e);
} + ')();';

injectJavaScript(code);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top