Skip to content

Instantly share code, notes, and snippets.

@roodni
Last active February 28, 2022 00:21
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 roodni/40fe3d5acba899f00e7d5f618045dd91 to your computer and use it in GitHub Desktop.
Save roodni/40fe3d5acba899f00e7d5f618045dd91 to your computer and use it in GitHub Desktop.
ニコニコ動画のコメントを正規表現でNGするスクリプト
// ==UserScript==
// @name nicovideo_regexp_comment_ng
// @version 0.1
// @description ニコニコ動画のコメントを正規表現でNGするスクリプト。EscキーでNGパターンを変更して保存できます。
// @match https://www.nicovideo.jp/watch/*
// ==/UserScript==
(function() {
'use strict';
const storageKey = 'regexp_comment_ng';
const patDefault = 'NG|厨|信者|批判|文句|民度|名人|幼稚|小学生|キッズ|ガキ|ゆとり';
let image_to_is_safe;
let patCurrent = null;
let regexp;
const updatePat = (pat) => {
if (pat !== patCurrent) {
try {
regexp = new RegExp(pat, 'i');
patCurrent = pat;
image_to_is_safe = new WeakMap();
localStorage.setItem(storageKey, pat);
console.log('NGパターンが更新された');
} catch(e) {
return false;
}
}
return true;
};
updatePat(localStorage.getItem(storageKey) ?? patDefault);
document.addEventListener('keyup', e => {
if (e.code === 'Escape') {
let pat = localStorage.getItem(storageKey);
while (true) {
pat = prompt('NGパターン設定', pat);
if (!pat || updatePat(pat)) {
break;
}
}
}
});
// createElementで生成されたcanvasのfillTextを監視
const canvas_to_text = new WeakMap();
const createElement = document.createElement;
document.createElement = function(tagName, ...args) {
const elem = createElement.call(this, tagName, ...args);
if (tagName === 'canvas') {
const ctx = elem.getContext('2d');
const fillText = ctx.fillText;
ctx.fillText = function(text, ...args) {
canvas_to_text.set(elem, text);
return fillText.call(this, text, ...args);
};
}
return elem;
};
// コメント描画canvasのdrawImageを監視
const modifyCommentCanvas = () => {
const commentCanvas = document.querySelector('.CommentRenderer > canvas');
if (!commentCanvas) {
setTimeout(modifyCommentCanvas, 100);
return;
}
const commentCtx = commentCanvas.getContext('2d');
const drawImage = commentCtx.drawImage;
commentCtx.drawImage = function(image, ...args) {
let is_safe = image_to_is_safe.get(image);
if (is_safe === undefined) {
const text = canvas_to_text.get(image);
if (text === undefined) {
is_safe = true;
} else {
const m = text.match(regexp);
if (m) {
console.log('NG', m[0]);
is_safe = false;
} else {
is_safe = true;
}
}
image_to_is_safe.set(image, is_safe);
}
if (is_safe) {
drawImage.call(this, image, ...args);
}
};
console.log('コメント描画のCanvasを書き換えた');
};
modifyCommentCanvas();
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment