Syntax highlighting: js
// ==UserScript==
// @name NHK ONE Consent Skipper
// @namespace http://tampermonkey.net/
// @version 1.0
// @description NHKプラスのCookieを自動で書き込みます。
// @match *://www.web.nhk/*
// @match *://news.web.nhk/*
// @match *://edu.web.nhk/*
// @run-at document-start
// @grant none
// ==/UserScript==
(function() {
'use strict';
const COOKIE_DOMAIN = ".web.nhk"; // 実際のCookieと同じドメイン
const SESSION_DURATION = 43200; // 中身のed用(12時間)
const COOKIE_MAX_AGE = 31536000; // Cookieの有効期限(1年)
// 指定したKeyを取り出す処理
const getCookie = (name) => {
const cookie = document.cookie.split('; ').find(row => row.startsWith(`${name}=`));
return cookie ? cookie.split('=')[1] : null;
};
// NHKが使用するISO 8601拡張形式に整形
// ミリ秒を.000に固定してシンプルにする
const formatISO = (date) => date.toISOString().replace(/\.\d{3}Z$/, '.000Z');
const now = new Date();
const future = new Date(now.getTime() + (SESSION_DURATION * 1000));
// 1. セッション開始と有効期限
const efmValue = JSON.stringify({ "sd": formatISO(now), "ed": formatISO(future) });
// 2. 受信エリアデータ(東京)
const consentValue = JSON.stringify({
"status": "optedin",
"entity": "household",
"area": { "areaId": "130", "jisx0402": "13113", "postal": "1508001", "pref": "13" }
});
// 更新が必要かどうかの判定
let needsUpdate = false;
const currentEfm = getCookie("efm");
if (!currentEfm) {
needsUpdate = true;
} else {
try {
const data = JSON.parse(decodeURIComponent(currentEfm));
// もしedが現在時刻を過ぎていたら更新
if (new Date(data.ed) < now) needsUpdate = true;
} catch (e) {
needsUpdate = true;
}
}
if (!getCookie("consentToUse")) {
needsUpdate = true;
}
if (needsUpdate && navigator.cookieEnabled) {
const cookieOption = `; path=/; domain=${COOKIE_DOMAIN}; max-age=${COOKIE_MAX_AGE}; SameSite=Lax`;
document.cookie = `efm=${efmValue}${cookieOption}`;
document.cookie = `consentToUse=${consentValue}${cookieOption}`;
// 正しくセットされたらリロードして反映
if (getCookie("efm") && getCookie("consentToUse")) {
console.log(`Updated: Session expires at ${formatISO(future)}`);
location.reload();
}
}
})();