I wrote a Google Chrome extension and the site that I want to use my extension on requires me to click or tab onto a text box (because I think it runs javaScript verification "onClick" only). I can get the text in the box with my extension using:
document.getElementById("input1").value = 'test';
But when I click submit, it thinks I did not enter anything in the "input1" text box because I never clicked it or tabbed on it.
Can someone help me get around this?
This question is related to
javascript
google-chrome
google-chrome-extension
you can raise the click event on an element by doing
// this must be done after input1 exists in the DOM
var element = document.getElementById("input1");
if (element) element.click();
Focus might be what your looking for. With tabbing or clicking I think u mean giving the element the focus. Same code as Russ (Sorry i stole it :P) but firing an other event.
// this must be done after input1 exists in the DOM
var element = document.getElementById("input1");
if (element) element.focus();
For simulating keyboard events in Chrome:
There is a related bug in webkit that keyboard events when initialized with initKeyboardEvent get an incorrect keyCode and charCode of 0: https://bugs.webkit.org/show_bug.cgi?id=16735
A working solution for it is posted in this SO answer.
Or even shorter, with only standard modern Javascript:
var first_link = document.getElementsByTagName('a')[0];
first_link.dispatchEvent(new MouseEvent('click'));
The new MouseEvent
constructor takes a required event type name, then an optional object (at least in Chrome). So you could, for example, set some properties of the event:
first_link.dispatchEvent(new MouseEvent('click', {bubbles: true, cancelable: true}));
Source: Stackoverflow.com