我不知道這是否會做你想做的,但它似乎運行「onkeypress」警報()。
<input type="text" id="blah" value="" onkeypress="javascript:alert ('Key Pressed');" />
<script type="text/javascript" language="Javascript">
// Create a keyboard event based on the function allowed by the browser (initKeyboardEvent or initKeyEvent)
var e = document.createEvent ("KeyboardEvent");
if (e.initKeyboardEvent)
{
e.initKeyboardEvent("keypress", true, true, window, false, false, false, false, 0, 65);
}
else if (e.initKeyEvent)
{
e.initKeyEvent("keypress", true, true, window, false, false, false, false, 0, 65);
}
// Focus the input and send the keypress
var inp = document.getElementById("blah");
inp.focus();
inp.dispatchEvent(e);
</script>
這段代碼是有道理的,但我似乎無法得到它的工作。它在一個Chrome擴展中,我認爲在這種情況下沒有什麼區別,但也許這就是爲什麼它沒有執行?沒有錯誤或任何其他的... – CdnXxRRODxX
哦。我從來沒有開發過Chrome擴展程序,才知道它的怪癖。快速谷歌搜索顯示:http://stackoverflow.com/questions/13987380/how-to-to-initialize-keyboard-event-with-given-char-keycode-in-a-chrome-extensio哪裏有人說有一個Webkit的bug,這可能是相關的?對不起,我不能幫助更多:( – Phil
如果擴展名是不向公衆發佈,你有沒有考慮寫它作爲一個Userscript?這可能讓你做你想要什麼,並會與支持他們的任何瀏覽器中工作(如。帶有Tampermonkey擴展的Chrome,帶有Greasemonkey的Firefox等)。 – Phil