Skip to content

Instantly share code, notes, and snippets.

@jr-codes
Created November 16, 2012 06:10
Show Gist options
  • Save jr-codes/4084704 to your computer and use it in GitHub Desktop.
Save jr-codes/4084704 to your computer and use it in GitHub Desktop.
Userscript Boilerplate
// ==UserScript==
// @name Userscript Name
// @namespace http://example.com/
// @description Userscript Description
// @match http://example.com/* (or @include * to include all pages)
// @version 1.0
// ==/UserScript==
// Emulate Greasemonkey's unsafeWindow in Chrome
window.unsafeWindow = window.unsafeWindow || (function() {
var el = document.createElement('p');
el.setAttribute('onclick', 'return window');
return el.onclick();
})();
// Inject JavaScript onto the page
function exec(fn) {
var script = document.createElement('script');
script.textContent = '(' + fn + ')();';
document.head.appendChild(script);
}
// Include external JS/CSS file onto the page
function include(url, type) {
type = (type || url.split('.').pop()).toLowerCase();
if (type === 'css') {
var link = document.createElement('link');
link.rel = 'stylesheet';
link.href = url;
document.head.appendChild(link);
} else if (type === 'js') {
var script = document.createElement('script');
script.src = url;
script.async = false;
document.head.appendChild(script);
} else {
throw new Error('Failed to include ' + url + ' due to unknown file type.');
}
}​
// Executes function asynchronously
function async(fn) {
setTimeout(fn, 0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment