Skip to content

Instantly share code, notes, and snippets.

@arantius
Created August 9, 2009 13:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arantius/164763 to your computer and use it in GitHub Desktop.
Save arantius/164763 to your computer and use it in GitHub Desktop.
// ==UserScript==
// @name Event Handler API Access Test
// ==/UserScript==
GM_setValue('test', 'works');
var console=document.getElementById('console');
console.value='';
function log(str) {
console.value=str+'\n'+console.value;
}
function listen(el, type) {
el.addEventListener(type, function(event) {
eventHandler(type, event);
}, false);
}
function eventHandler(type, event) {
var access=GM_getValue('test', 'FAILS!!');
if ('undefined'==typeof access) access='FAILS!!';
log('API access: '+access);
log('handled event: '+type);
log('------------------------------');
}
listen(document.body, 'DOMNodeInserted');
listen(window, 'load');
listen(document.getElementById('click'), 'click');
listen(document.getElementById('input'), 'focus');
listen(document.getElementById('input'), 'blur');
listen(document.getElementById('input'), 'change');
listen(document.getElementById('input'), 'keyup');
listen(document.getElementById('input'), 'keydown');
listen(document.getElementById('input'), 'keypress');
listen(document.getElementById('form1'), 'reset');
listen(document.getElementById('form2'), 'reset');
listen(document.getElementById('form1'), 'submit');
listen(document.getElementById('form2'), 'submit');
/*
When run on the page below, this script will fail, logging:
Error: Greasemonkey access violation: unsafeWindow cannot call GM_getValue.
To the error console, and getting undefined in "access".
<html>
<head>
<script type="text/javascript">
function ins() {
var el=document.createElement('div');
document.body.appendChild(el);
}
function reset1() {
var el=document.getElementById('form1');
el.reset();
}
function submit1() {
var el=document.getElementById('form1');
el.submit();
}
</script>
</head>
<body>
<textarea id='console' class='noprotect' rows='20' cols='' style='width: 95%;'></textarea>
<hr>
Fail:
<form id='form1' action='#' onsubmit='return false;'>
<button type='button' onclick='ins()'>DOMNodeInserted</button>
<button type='button' onclick='reset1()'>Reset 1</button>
<button type='button' onclick='submit1()'>Submit 1?</button>
</form>
<hr>
Work:
<form id='form2' action='#' onsubmit='return false;'>
<button type='button' id='click'>click</button>
<input id='input' size='60' value='Focus / Blur / Keys / Change'>
<input type='reset' value='Reset 2'>
<input type='submit' value='Submit 2'>
</form>
</body>
</html>
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment