Skip to content

Instantly share code, notes, and snippets.

@cxx
Created August 9, 2015 02:36
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 cxx/4e3af4b26add8e2b51d4 to your computer and use it in GitHub Desktop.
Save cxx/4e3af4b26add8e2b51d4 to your computer and use it in GitHub Desktop.
マンガ図書館Zのサムネイルから本棚に登録
// ==UserScript==
// @name サムネイルから本棚に登録
// @namespace http://twitter.com/cxx
// @include http://www.mangaz.com/*
// @include http://r18.mangaz.com/*
// @version 0.1.0
// ==/UserScript==
"use strict";
if (!Array.from)
Array.from = Function.prototype.call.bind(Array.prototype.slice);
function $(selector, element) {
return (element || document).querySelector(selector);
}
function $$(selector, element) {
return Array.from((element || document).querySelectorAll(selector));
}
function parseHTML(html) {
let range = document.createRange();
range.selectNodeContents(document.body);
let fragment = range.createContextualFragment(html);
return fragment.removeChild(fragment.firstElementChild);
}
function postRequest(url, data, onSuccess, onError) {
let req = new XMLHttpRequest();
if (onSuccess)
req.addEventListener("load", onSuccess);
if (onError) {
["error", "abort", "timeout"].forEach(function (type) {
req.addEventListener(type, onError);
});
}
req.open("POST", url);
req.timeout = 5000;
let formData = new FormData();
for (let key in data)
formData.append(key, data[key]);
req.send(formData);
}
function addShelfButton(elements) {
elements.forEach(function (item) {
let button = parseHTML("<button class='add-btn'>+</button>");
button.addEventListener("click", addToShelf);
$(".bookList-box", item).appendChild(button);
});
}
function addToShelf() {
let button = this;
let baid = $("a", button.parentNode).href.match(/\d+$/)[0];
postRequest("/bookshelf/add.json",
{ baid, origin: location.origin },
function () {
button.textContent = "\u2713";
button.classList.add("added");
},
function () { alert("error"); });
}
document.head.insertAdjacentHTML("beforeend",
`<style>
.add-btn {
position: absolute;
top: 0;
right: 0;
width: 40px;
height: 40px;
border: 0;
font-size: 30px;
opacity: 0.8;
}
.add-btn.added {
background-color: #8f8;
}
</style>`);
new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
addShelfButton(
Array.prototype.filter.call(mutation.addedNodes, function (node) {
return node.nodeType == Node.ELEMENT_NODE;
})
);
});
}).observe($(".bookList"), { childList: true });
addShelfButton($$(".bookList > li"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment