Skip to content

Instantly share code, notes, and snippets.

@syoichi
Created July 16, 2012 06:03
Show Gist options
  • Save syoichi/3120982 to your computer and use it in GitHub Desktop.
Save syoichi/3120982 to your computer and use it in GitHub Desktop.
Chrome 20.0.1132.57のUser Scriptで利用できるGM関数とその実装
// ref. http://wiki.greasespot.net/Cross-browser_userscripting#Google_Chrome
// Comparison Table: https://github.com/scriptish/scriptish/wiki/Comparison-Table
// GM_setValue、GM_getValue、GM_registerMenuCommandは関数として呼び出せるものの、以下のようにChromeでは対応していない
/*
function () {
console.log("%s is not supported.", name);
}
*/
// Greasemonkey: http://wiki.greasespot.net/GM_addStyle
// Scriptish: https://github.com/scriptish/scriptish/wiki/GM_addStyle
function GM_addStyle(css) {
var parent = document.getElementsByTagName("head")[0];
if (!parent) {
parent = document.documentElement;
}
var style = document.createElement("style");
style.type = "text/css";
var textNode = document.createTextNode(css);
style.appendChild(textNode);
parent.appendChild(style);
}
// Greasemonkey: http://wiki.greasespot.net/GM_log
// Scriptish: https://github.com/scriptish/scriptish/wiki/GM_log
function GM_log(message) {
window.console.log(message);
}
// Greasemonkey: http://wiki.greasespot.net/GM_openInTab
// Scriptish: https://github.com/scriptish/scriptish/wiki/GM_openInTab
function GM_openInTab(url) {
window.open(url, "");
}
// Greasemonkey: http://wiki.greasespot.net/GM_xmlhttpRequest
// Scriptish: https://github.com/scriptish/scriptish/wiki/GM_xmlhttpRequest
function GM_xmlhttpRequest(details) {
function setupEvent(xhr, url, eventName, callback) {
xhr[eventName] = function () {
var isComplete = xhr.readyState == 4;
var responseState = {
responseText: xhr.responseText,
readyState: xhr.readyState,
responseHeaders: isComplete ? xhr.getAllResponseHeaders() : "",
status: isComplete ? xhr.status : 0,
statusText: isComplete ? xhr.statusText : "",
finalUrl: isComplete ? url : ""
};
callback(responseState);
};
}
var xhr = new XMLHttpRequest();
var eventNames = ["onload", "onerror", "onreadystatechange"];
for (var i = 0; i < eventNames.length; i++ ) {
var eventName = eventNames[i];
if (eventName in details) {
setupEvent(xhr, details.url, eventName, details[eventName]);
}
}
xhr.open(details.method, details.url);
if (details.overrideMimeType) {
xhr.overrideMimeType(details.overrideMimeType);
}
if (details.headers) {
for (var header in details.headers) {
xhr.setRequestHeader(header, details.headers[header]);
}
}
xhr.send(details.data ? details.data : null);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment