I'm working on a javascript keyboard that seeks to enable users to type in various African languages.Currently, this works fine in IE8 and firefox but not google chrome, and I'm actually stuck on this one.What I want to accomplish is for example, to type(on my physical keyboard) 'q'(keyCode=113) and get '?'(keyCode=603) as the output but currently, my code does nothing in google chrome. The relevant portion of my code is as follows:
var k_layouts = {};
k_layouts.Akan = {88:390,113:603};//keyCode mappings for Akan language
k_layouts.Ga = {120:596,81:400};//keyCode mappings for Ga language
var current_layout = "";
//function that maps the keyCode of a **typed** key to that of the **expected** key
function map_key_code(keycode){
if(k_layouts[current_layout] && k_layouts[current_layout][keycode])
return k_layouts[current_layout][keycode];
return keycode;
}
//function that actually changes the keyCode of a **typed** key to the **expected** value
function handle_keypress(ev){
var ev = ev || window.event;
if(ev.bubbles != null ||!ev.bubbles)
return true;
var target = ev.target || ev.srcElement;
var keyCode = window.event? ev.keyCode: ev.which;
if(keyCode == 0)
return true;
var newKeyCode = map_key_code(keyCode);
if(newKeyCode == keyCode)
return true;
if(target.addEventListener){ //for chrome and firefox
//cancel event
ev.preventDefault();
ev.stopPropagation();
//create new event with the keycode changed
var evt = document.createEvent("KeyboardEvent");
try{//for firefox(works fine)
evt.initKeyEvent("keypress",false,true,document.defaultView,ev.ctrlKey,ev.altKey,ev.shiftKey,ev.metaKey,newKeyCode,newKeyCode);
}
catch(e){// for google chrome(does not work as expected)
evt.initKeyboardEvent("keydown",false,true,document.defaultView,ev.ctrlKey,ev.altKey,ev.shiftKey,ev.metaKey,newKeyCode,newKeyCode);
}
//dispatch new event
target.dispatchEvent(evt);
}
else if(target.attachEvent){// works for IE
ev.keyCode = newKeyCode;
}
}
Is there a way of achieving what I seek to do in chrome?Or, is there something I'm missing in my approach?I'd be glad for any help, and any thoughts.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…