// ==UserScript== // @name Bili IP Lens · B站评论 IP 属地 // @name:en Bili IP Lens · Bilibili Comment IP Region // @namespace https://github.com/8TrafficAI/bili-ip-lens // @version 0.1.1 // @description 显示 B站评论已有的 IP 属地,油猴菜单一键开关并保存设置;不额外查询 IP,不上传评论数据。 // @description:en Show the IP region already supplied with Bilibili comments. Toggle instantly from the userscript menu with a saved preference. No IP lookup or data upload. // @author 8TrafficAI contributors // @copyright 2026 Bili IP Lens contributors; 2023-present MaxChang3 // @license MIT // @homepageURL https://github.com/8TrafficAI/bili-ip-lens // @supportURL https://github.com/8TrafficAI/bili-ip-lens/issues // @match https://www.bilibili.com/* // @match https://t.bilibili.com/* // @match https://space.bilibili.com/* // @run-at document-start // @noframes // @sandbox JavaScript // @grant unsafeWindow // @grant GM_getValue // @grant GM_setValue // @grant GM_registerMenuCommand // @grant GM_unregisterMenuCommand // @grant GM_addValueChangeListener // ==/UserScript== /* Generated by scripts/build-userscript.mjs; edit extension/page.js or userscript/settings.js and rebuild. All functional code is included here. No external script is downloaded or injected. Update checks are left to the userscript manager, using the source from which the user installs this file. MIT License Copyright (c) 2026 Bili IP Lens contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # Third-party notices ## BiliReveal The modern comment component integration in `page.js` is adapted from [BiliReveal](https://github.com/maxchang3/BiliReveal), specifically [`src/injection/lit-component.ts`](https://github.com/maxchang3/BiliReveal/blob/main/src/injection/lit-component.ts). Source blob SHA when reviewed: `cbac111be4f9d68fa569b9e2bb9add81e7d14e22`. Modifications: independent MV3 packaging; persistent user-controlled toggle; extension-specific labels; native label detection; detached component cleanup; late component registration support; popup and toolbar state. MIT License Copyright (c) 2023-present MaxChang3 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ (() => { 'use strict'; // Use the page's objects rather than sandbox DOM wrappers so component.data // and customElements refer to Bilibili's actual JavaScript objects. const page = unsafeWindow; const document = page.document; const customElements = page.customElements; const CustomEvent = page.CustomEvent; const Event = page.Event; const queueMicrotask = page.queueMicrotask.bind(page); /* * Modern Bilibili comment integration adapted from BiliReveal (MIT). * Copyright (c) 2023-present MaxChang3. See THIRD_PARTY_NOTICES.md. * Changes: live toggle, own labels, native-label detection, bounded lifecycle, * late registration support, and no network or comment-content transport. */ (() => { 'use strict'; const NAME = 'bili-comment-action-buttons-renderer'; const MARKER = 'data-bili-ip-lens-userscript'; const SETTINGS = 'bili-ip-lens-userscript:settings'; const STATUS = 'bili-ip-lens-userscript:status'; const READY = 'bili-ip-lens-userscript:ready'; const REQUEST = 'bili-ip-lens-userscript:request-status'; const instances = new Set(); const patched = new WeakSet(); let enabled = false; let statusScheduled = false; function locationText(instance) { const value = instance.data?.reply_control?.location; if (typeof value !== 'string') return ''; const text = value.trim().replace(/^IP\s*属地\s*[::]?\s*/i, ''); return text && text.length <= 80 ? `IP属地:${text}` : ''; } function publishStatus() { statusScheduled = false; let count = 0; for (const instance of instances) { if (!instance.isConnected) { instance.shadowRoot?.querySelector(`[${MARKER}]`)?.remove(); instances.delete(instance); } else if (instance.shadowRoot?.querySelector(`[${MARKER}]`)) { count += 1; } } document.dispatchEvent(new CustomEvent(STATUS, { detail: { count, supported: !!customElements.get(NAME) }, })); } function scheduleStatus() { if (statusScheduled) return; statusScheduled = true; queueMicrotask(publishStatus); } function sync(instance) { const root = instance.shadowRoot; if (!root) return; let badge = root.querySelector(`[${MARKER}]`); const text = enabled ? locationText(instance) : ''; const nativeLabel = root.querySelector('#location, .reply-location, [data-ip-location], [data-bili-ip-lens]'); const pubdate = root.querySelector('#pubdate'); if (!text || !pubdate || nativeLabel?.textContent?.trim()) { badge?.remove(); scheduleStatus(); return; } if (!badge) { badge = document.createElement('span'); badge.setAttribute(MARKER, ''); // Inherit Bilibili's metadata color, type, spacing, and dark theme. badge.style.cssText = 'font:inherit;color:inherit;white-space:nowrap;'; pubdate.insertAdjacentElement('afterend', badge); } badge.textContent = text; badge.title = 'B站为这条评论提供的 IP 属地'; scheduleStatus(); } function safelySync(instance) { try { instances.add(instance); sync(instance); } catch { // A site renderer change must never interrupt comment rendering. } } function patch(Constructor) { if (!Constructor || patched.has(Constructor)) return; const original = Constructor.prototype.update; if (typeof original !== 'function') return; try { Constructor.prototype.update = function (...args) { const result = Reflect.apply(original, this, args); safelySync(this); return result; }; patched.add(Constructor); } catch { // A frozen site prototype must still be registered and render normally. } } function discover(root) { for (const instance of root.querySelectorAll(NAME)) safelySync(instance); // Existing comments can live several open shadow roots deep. for (const element of root.querySelectorAll('*')) { if (element.shadowRoot) discover(element.shadowRoot); } } const existing = customElements.get(NAME); if (existing) { patch(existing); } else { const originalDefine = customElements.define; const wrappedDefine = function (name, Constructor, options) { if (name === NAME) patch(Constructor); const result = Reflect.apply(originalDefine, this, [name, Constructor, options]); // Stop intercepting the registry as soon as our one component exists. if (name === NAME && customElements.define === wrappedDefine) { customElements.define = originalDefine; } return result; }; customElements.define = wrappedDefine; } document.addEventListener(SETTINGS, (event) => { if (typeof event.detail !== 'boolean') return; enabled = event.detail; discover(document); for (const instance of instances) { if (!instance.isConnected) { instance.shadowRoot?.querySelector(`[${MARKER}]`)?.remove(); instances.delete(instance); } else safelySync(instance); } scheduleStatus(); }); document.addEventListener(REQUEST, publishStatus); document.dispatchEvent(new Event(READY)); })(); // Userscript-only persistence and menu. The rendering integration above is // generated from extension/page.js with a separate marker and event namespace. (() => { 'use strict'; const KEY = 'bili-ip-lens-enabled'; let enabled = false; let initialized = false; let saving = false; let revision = 0; let menuId; function publishSettings() { document.dispatchEvent(new CustomEvent('bili-ip-lens-userscript:settings', { detail: enabled, })); } function updateMenu() { if (typeof GM_registerMenuCommand !== 'function') return; const canReplace = typeof GM_unregisterMenuCommand === 'function'; if (menuId !== undefined) { if (!canReplace) return; GM_unregisterMenuCommand(menuId); } const label = canReplace ? (enabled ? '关闭 IP 属地显示(已开启)' : '开启 IP 属地显示(已关闭)') : '切换 IP 属地显示'; menuId = GM_registerMenuCommand(label, toggle); } function apply(value) { enabled = value !== false; initialized = true; publishSettings(); updateMenu(); } async function toggle() { if (!initialized || saving) return; saving = true; const next = !enabled; const beforeWrite = revision; try { await GM_setValue(KEY, next); // Local or remote storage notifications may already carry a newer value. if (revision === beforeWrite) apply(next); } catch { // A failed write must not claim a persistent preference was saved. console.warn('[Bili IP Lens] 无法保存开关,已保留原状态。'); } finally { saving = false; } } if (typeof GM_addValueChangeListener === 'function') { GM_addValueChangeListener(KEY, (_key, _oldValue, newValue) => { revision += 1; apply(newValue); }); } const beforeRead = revision; try { Promise.resolve(GM_getValue(KEY, true)).then((value) => { if (revision === beforeRead) apply(value); }).catch(() => { if (revision !== beforeRead) return; // Remain OFF if reading preferences fails, but allow a manual retry. apply(false); console.warn('[Bili IP Lens] 无法读取设置;可从油猴菜单手动开启。'); }); } catch { apply(false); console.warn('[Bili IP Lens] 无法读取设置;可从油猴菜单手动开启。'); } })(); })();