// ==UserScript== // @name Cloudflare DNS 快捷面板 // @namespace local.cloudflare.dns.quick // @version 1.2.4 // @license MIT // @homepageURL https://github.com/Rain48698/cloudflare-dns-quick-panel // @supportURL https://github.com/Rain48698/cloudflare-dns-quick-panel/issues // @source https://github.com/Rain48698/cloudflare-dns-quick-panel // @tag cloudflare // @tag dns // @tag dns-manager // @description 在任意网站手动启用 Cloudflare DNS 面板;启用后该网站默认显示(菜单或 Alt+Shift+D) // @match *://*/* // @grant GM_getValue // @grant GM_setValue // @grant GM_xmlhttpRequest // @grant GM_registerMenuCommand // @connect api.cloudflare.com // @noframes // @run-at document-idle // ==/UserScript== (function () { 'use strict'; if (document.getElementById('cf-dns-quick-host')) return; const API_BASE = 'https://api.cloudflare.com/client/v4'; const PROXYABLE = new Set(['A', 'AAAA', 'CNAME']); const EDITABLE = new Set(['A', 'AAAA', 'CNAME', 'TXT', 'MX']); const TTL_CHOICES = [1, 60, 120, 300, 600, 1800, 3600, 7200, 18000, 43200, 86400]; const PLACEHOLDERS = { A: 'IPv4 地址,例如 203.0.113.10', AAAA: 'IPv6 地址,例如 2001:db8::1', CNAME: '目标主机名,例如 example.com', TXT: '文本内容', MX: '邮件服务器,例如 mx.example.com', }; const state = { token: GM_getValue('cfToken', '') || '', zones: [], zoneId: GM_getValue('cfZoneId', '') || '', zoneName: GM_getValue('cfZoneName', '') || '', records: [], query: '', type: '', editingId: '', pendingDeleteId: '', busy: false, loaded: false, view: 'main', }; let deleteTimer = 0; let toastTimer = 0; let searchTimer = 0; /* ---------------- 样式 ---------------- */ const CSS = ` :host { all: initial; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Microsoft YaHei", system-ui, sans-serif; } * { box-sizing: border-box; } button, input, select { font: inherit; color: inherit; } button { cursor: pointer; } button:disabled { opacity: .55; cursor: default; } .pill { position: fixed; right: 22px; bottom: 22px; z-index: 2147483646; height: 42px; padding: 0 16px 0 14px; display: inline-flex; align-items: center; gap: 7px; border: 0; border-radius: 21px; background: linear-gradient(135deg, #f9a13a, #e45e06); color: #fff; font-size: 13px; font-weight: 700; letter-spacing: .03em; box-shadow: 0 6px 20px rgba(228, 94, 6, .38); } .pill:hover { filter: brightness(1.05); } .pill.active { box-shadow: 0 0 0 3px rgba(246, 130, 31, .28), 0 6px 20px rgba(228, 94, 6, .4); } .panel { position: fixed; right: 22px; bottom: 74px; z-index: 2147483647; width: min(760px, calc(100vw - 32px)); height: min(560px, calc(100vh - 110px)); display: flex; flex-direction: column; background: #f6f7f9; color: #1c1d21; border: 1px solid #e0e3e8; border-radius: 12px; box-shadow: 0 24px 64px rgba(15, 23, 42, .28); overflow: hidden; font-size: 13px; line-height: 1.45; } .panel.hidden, .view.hidden, .create.hidden, .empty.hidden, .status.hidden, #newProxiedWrap.hidden, #newPriorityWrap.hidden { display: none !important; } .head { display: flex; align-items: center; gap: 8px; padding: 10px 12px; background: #fff; border-bottom: 1px solid #e4e6ea; } .brand { display: flex; align-items: center; gap: 7px; font-weight: 650; font-size: 13.5px; white-space: nowrap; } .brand svg { width: 19px; height: 19px; color: #f6821f; } .zone { margin-left: auto; max-width: 210px; height: 30px; padding: 0 8px; border: 1px solid #d3d7dd; border-radius: 6px; background: #fff; font-weight: 550; text-overflow: ellipsis; } .icon { width: 30px; height: 30px; display: inline-flex; align-items: center; justify-content: center; border: 1px solid #d3d7dd; border-radius: 6px; background: #fff; color: #7a8087; font-size: 15px; line-height: 1; } .icon:hover { color: #1c1d21; border-color: #f6821f; } .view { display: flex; flex-direction: column; flex: 1 1 auto; min-height: 0; } /* 设置 */ .settings-card { margin: 18px; padding: 18px; background: #fff; border: 1px solid #e4e6ea; border-radius: 10px; } .settings-card h3 { margin: 0 0 6px; font-size: 14px; } .settings-card p { margin: 0 0 12px; color: #757b83; font-size: 12.5px; line-height: 1.6; } .settings-card code { padding: 1px 5px; border: 1px solid #e4e6ea; border-radius: 4px; background: #f6f7f9; font-size: 11.5px; } .lbl { display: block; margin: 10px 0 5px; color: #757b83; font-size: 11.5px; font-weight: 600; } .row { display: flex; align-items: flex-end; gap: 8px; margin-bottom: 8px; flex-wrap: wrap; } .row.small { align-items: center; color: #757b83; font-size: 12px; } .grow { flex: 1 1 200px; min-width: 0; } .spacer { flex: 1; } .settings-card input, .settings-card select, .create input, .create select, .toolbar input { height: 31px; padding: 0 9px; border: 1px solid #d3d7dd; border-radius: 6px; background: #fff; outline: none; } .settings-card input { width: 100%; } .settings-card input:focus, .create input:focus, .create select:focus, .toolbar input:focus, .zone:focus { border-color: #f6821f; box-shadow: 0 0 0 2px rgba(246, 130, 31, .16); } .field { display: flex; flex-direction: column; gap: 5px; } .fine { margin: 10px 0 0; color: #9aa0a6; font-size: 11.5px; } .msg { font-size: 12px; color: #757b83; } .msg.error { color: #d92d20; } .msg.ok { color: #12805c; } /* 工具条 */ .toolbar { display: flex; align-items: center; gap: 8px; padding: 10px 12px 8px; } .toolbar .search { flex: 0 0 190px; } .chips { display: flex; gap: 4px; flex-wrap: wrap; } .chip { height: 26px; padding: 0 9px; border: 1px solid #d3d7dd; border-radius: 999px; background: #fff; color: #7a8087; font-size: 12px; font-weight: 550; } .chip:hover { color: #1c1d21; } .chip.on { background: #fff3e6; border-color: #f6821f; color: #df6c00; } button.primary { height: 31px; padding: 0 12px; border: 1px solid #f6821f; border-radius: 6px; background: #f6821f; color: #fff; font-weight: 600; } button.primary:hover { background: #df6c00; border-color: #df6c00; } button.ghost { height: 31px; padding: 0 12px; border: 1px solid #d3d7dd; border-radius: 6px; background: #fff; color: #1c1d21; } button.ghost:hover { border-color: #f6821f; } .add-btn { margin-left: auto; flex: none; } /* 新增表单 */ .create { display: flex; flex-direction: column; gap: 8px; margin: 0 12px 10px; padding: 10px; background: #fff; border: 1px solid #e4e6ea; border-left: 3px solid #f6821f; border-radius: 8px; } .create .row { margin: 0; } .type-select { width: 88px; flex: none; } .name-input { flex: 0 1 200px; } .content-input { flex: 1 1 auto; } .create .row.small select { width: 86px; } .create label { display: inline-flex; align-items: center; gap: 6px; white-space: nowrap; } .create input[type="number"] { width: 62px; } .create input[type="checkbox"] { height: auto; } .status { padding: 0 12px 8px; color: #757b83; font-size: 12px; display: flex; align-items: center; gap: 7px; } .status.loading::before { content: ""; width: 11px; height: 11px; border: 2px solid #d3d7dd; border-top-color: #f6821f; border-radius: 50%; animation: cfspin .7s linear infinite; } @keyframes cfspin { to { transform: rotate(360deg); } } .table-wrap { flex: 1 1 auto; margin: 0 12px; min-height: 90px; overflow: auto; background: #fff; border: 1px solid #e4e6ea; border-radius: 8px; } table { width: 100%; border-collapse: collapse; table-layout: fixed; } thead th { position: sticky; top: 0; z-index: 1; padding: 7px 8px; background: #fff; border-bottom: 1px solid #e4e6ea; color: #7a8087; font-size: 11px; font-weight: 600; text-align: left; } tbody td { padding: 6px 8px; border-bottom: 1px solid #eef0f3; vertical-align: middle; } tbody tr:last-child td { border-bottom: 0; } tbody tr:hover { background: #fffaf4; } .rec-name, .rec-content { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 12px; } .rec-name { font-weight: 600; } .badge { display: inline-block; min-width: 40px; padding: 1px 5px; border-radius: 4px; background: #f6f7f9; border: 1px solid #e4e6ea; color: #7a8087; font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 10.5px; font-weight: 600; text-align: center; } .badge.type-a { color: #2563eb; background: #eff5ff; border-color: #d7e6ff; } .badge.type-aaaa { color: #7c3aed; background: #f5f0ff; border-color: #e6dbff; } .badge.type-cname { color: #0f766e; background: #ecfdf8; border-color: #c9f0e5; } .badge.type-txt { color: #a16207; background: #fef9e7; border-color: #f6e8b8; } .badge.type-mx { color: #be185d; background: #fdf0f6; border-color: #f7d4e3; } .proxy { display: inline-flex; align-items: center; gap: 5px; font-size: 11.5px; font-weight: 550; color: #9aa0a6; white-space: nowrap; } .proxy::before { content: ""; width: 6px; height: 6px; border-radius: 50%; background: currentColor; } .proxy.on { color: #12805c; } .muted { color: #9aa0a6; } .mx-priority { display: block; margin-top: 2px; font-size: 11px; } .row-actions { display: flex; gap: 5px; justify-content: flex-end; } button.mini { height: 24px; padding: 0 8px; border: 1px solid #d3d7dd; border-radius: 5px; background: #fff; color: #1c1d21; font-size: 11.5px; } button.mini:hover { border-color: #f6821f; color: #df6c00; } button.mini.primary { background: #f6821f; border-color: #f6821f; color: #fff; } button.mini.danger { border-color: #d92d20; background: #fef1f0; color: #d92d20; } td .cell-input { width: 100%; height: 27px; padding: 0 6px; border: 1px solid #d3d7dd; border-radius: 5px; background: #fff; outline: none; font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 12px; } td select.cell-input { font-family: inherit; } .content-edit { display: flex; gap: 5px; } .content-edit .priority { flex: 0 0 62px; font-family: inherit; } tr.editing, tr.editing:hover { background: #fff3e6; } .empty { padding: 34px 12px; text-align: center; color: #9aa0a6; font-size: 12.5px; } .foot { display: flex; align-items: center; justify-content: space-between; padding: 8px 12px; color: #9aa0a6; font-size: 11.5px; } .foot-meta { display: inline-flex; align-items: center; gap: 10px; } .repo-link { color: #df6c00; font-weight: 600; text-decoration: none; } .repo-link:hover { text-decoration: underline; } .toast { position: absolute; left: 50%; bottom: 16px; transform: translate(-50%, 8px); max-width: 80%; padding: 8px 14px; border-radius: 7px; background: #1f2937; color: #fff; font-size: 12.5px; box-shadow: 0 8px 24px rgba(0, 0, 0, .26); opacity: 0; pointer-events: none; transition: opacity .16s ease, transform .16s ease; } .toast.show { opacity: 1; transform: translate(-50%, 0); } .toast.error { background: #d92d20; } /* 手机 / 窄屏:整屏面板 + 记录卡片 */ @media (max-width: 700px) { .pill { right: 12px; bottom: 12px; height: 40px; padding: 0 14px 0 12px; font-size: 12px; } .panel { left: 8px; right: 8px; top: 8px; bottom: 64px; width: auto; height: auto; border-radius: 10px; } .head { padding: 8px 10px; gap: 6px; } .brand-text { display: none; } .brand svg { width: 18px; height: 18px; } .zone { flex: 1 1 auto; max-width: none; min-width: 0; margin-left: 0; } .icon { width: 28px; height: 28px; } .settings-card { margin: 10px; padding: 14px; } .settings-card .row { align-items: stretch; } .settings-card .row .grow { flex: 1 1 100%; } .field { flex: 1 1 100%; } .field select, .field input[type="number"] { width: 100%; } .toolbar { flex-wrap: wrap; gap: 6px; padding: 8px 10px 6px; } .toolbar .search { flex: 1 1 100%; height: 32px; } .chips { order: 2; flex: 1 1 auto; flex-wrap: nowrap; overflow-x: auto; scrollbar-width: none; } .chips::-webkit-scrollbar { display: none; } .chip { flex: none; } .add-btn { order: 3; height: 30px; padding: 0 10px; } .create { margin: 0 10px 8px; padding: 9px; } .create .row { flex-wrap: wrap; } .create .row .type-select { flex: 0 0 100%; width: 100%; } .create .name-input, .create .content-input { flex: 1 1 100%; } .create .row.small .spacer { display: none; } .create .row.small { justify-content: flex-end; } .status { padding: 0 10px 6px; } .table-wrap { margin: 0 10px; overflow-y: auto; } table, tbody, tr, td { display: block; width: auto; } colgroup, thead { display: none; } table { table-layout: auto; width: 100%; } tbody tr { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 5px 8px; padding: 9px 10px; border-bottom: 1px solid #eef0f3; } tbody tr:last-child { border-bottom: 0; } tbody td { padding: 0; border: 0; min-width: 0; } tbody td:nth-child(1) { grid-column: 1; grid-row: 1; align-self: center; } tbody td:nth-child(2) { grid-column: 2; grid-row: 1; justify-self: end; } tbody td:nth-child(3) { grid-column: 1 / -1; grid-row: 2; } tbody td:nth-child(4) { grid-column: 1; grid-row: 3; align-self: center; } tbody td:nth-child(5) { grid-column: 2; grid-row: 3; justify-self: end; } tbody td:nth-child(6) { grid-column: 1 / -1; grid-row: 4; } td:nth-child(4)::before { content: "代理 "; color: #9aa0a6; font-size: 11px; } td:nth-child(5)::before { content: "TTL "; color: #9aa0a6; font-size: 11px; } .rec-name, .rec-content { white-space: normal; overflow-wrap: anywhere; font-size: 12.5px; } .row-actions { justify-content: flex-start; margin-top: 2px; } .row-actions button.mini { height: 26px; padding: 0 10px; } .foot { padding: 6px 10px; } .foot-hint { display: none; } .empty { padding: 28px 10px; } .toast { bottom: 10px; max-width: calc(100% - 24px); } } `; /* ---------------- DOM ---------------- */ const host = document.createElement('div'); host.id = 'cf-dns-quick-host'; const shadow = host.attachShadow({ mode: 'open' }); shadow.innerHTML = ` DNS DNS 快捷面板 ↻ ⚙ ✕ 连接 Cloudflare 权限:Zone → DNS → Edit(区域 → DNS → 编辑;必须,不是「DNS 设置」);Zone → Zone → Read(区域 → 读取;可选,用于列出/切换域名)。没有 Zone Read 时,令牌仍能增删改记录;在下面手动填 Zone ID 即可。创建 API 令牌 ↗ API 令牌 显示 手动 Zone ID(可选) 域名(可选) 保存并验证 返回 令牌只保存在本机油猴脚本存储中,请求直连 api.cloudflare.com。项目主页:GitHub 全部 A AAAA CNAME TXT MX + 新增 A AAAA CNAME TXT MX TTL 代理 优先级 保存 取消 名称类型内容代理TTL操作 暂无记录 `; document.documentElement.append(host); /* ---------------- 站点开关 ---------------- */ const ENABLED_SITES_KEY = 'cfEnabledSites'; const DEFAULT_ENABLED_SITES = ['dash.cloudflare.com']; function getEnabledSites() { const stored = GM_getValue(ENABLED_SITES_KEY, null); return Array.isArray(stored) ? stored : DEFAULT_ENABLED_SITES.slice(); } function isSiteEnabled() { return getEnabledSites().includes(location.hostname); } function setSiteEnabled(enabled) { const sites = getEnabledSites().filter((site) => site !== location.hostname); if (enabled) sites.push(location.hostname); GM_setValue(ENABLED_SITES_KEY, sites); } function showHost() { host.style.display = ''; } function hideHost() { closePanel(); host.style.display = 'none'; } if (!isSiteEnabled()) { host.style.display = 'none'; } const $ = (id) => shadow.getElementById(id); /* ---------------- API ---------------- */ function cf(path, { method = 'GET', body, token } = {}) { const key = token !== undefined ? token : state.token; return new Promise((resolve, reject) => { if (!key) { reject(new Error('尚未配置 API 令牌')); return; } GM_xmlhttpRequest({ method, url: API_BASE + path, headers: { Authorization: 'Bearer ' + key, 'Content-Type': 'application/json', }, data: body === undefined ? undefined : JSON.stringify(body), timeout: 20000, onload(res) { let data = null; try { data = JSON.parse(res.responseText); } catch { data = null; } if (res.status >= 200 && res.status < 300 && data && data.success === true) { resolve(data); return; } const errors = data && Array.isArray(data.errors) ? data.errors : []; const detail = errors .map((item) => item.message + (item.code ? '(' + item.code + ')' : '')) .join(';'); reject(new Error(detail || 'HTTP ' + res.status)); }, onerror() { reject(new Error('网络请求失败')); }, ontimeout() { reject(new Error('请求超时')); }, }); }); } async function getAll(path, perPage, maxPages = 20) { const out = []; let totalPages = 1; for (let page = 1; page <= totalPages && page <= maxPages; page += 1) { const sep = path.includes('?') ? '&' : '?'; const data = await cf(path + sep + 'per_page=' + perPage + '&page=' + page); if (Array.isArray(data.result)) out.push(...data.result); totalPages = Number(data.result_info && data.result_info.total_pages) || 1; } return out; } /* ---------------- 工具 ---------------- */ function persistZone() { GM_setValue('cfZoneId', state.zoneId); GM_setValue('cfZoneName', state.zoneName); } function currentZoneName() { if (state.zoneName) return state.zoneName; const zone = state.zones.find((item) => item.id === state.zoneId); return zone ? zone.name : ''; } function displayName(fqdn) { const zone = currentZoneName(); if (!zone) return fqdn; if (fqdn === zone) return '@'; if (fqdn.endsWith('.' + zone)) return fqdn.slice(0, -(zone.length + 1)); return fqdn; } function toFqdn(value) { const name = value.trim().replace(/\.$/, ''); const zone = currentZoneName(); if (!name || name === '@') { if (!zone) throw new Error('当前不知道域名后缀,请填写完整记录名'); return zone; } if (zone && (name === zone || name.endsWith('.' + zone))) return name; if (!zone) { if (!name.includes('.')) throw new Error('当前不知道域名后缀,请填写完整记录名'); return name; } return name + '.' + zone; } function zoneFromUrl() { const segment = location.pathname.split('/').filter(Boolean)[1]; if (!segment) return ''; let decoded = segment; try { decoded = decodeURIComponent(segment); } catch { // keep raw } const zone = state.zones.find((item) => item.name === decoded); return zone ? zone.id : ''; } function setStatus(text, loading = false) { const node = $('status'); node.textContent = text || ''; node.classList.toggle('hidden', !text); node.classList.toggle('loading', Boolean(text) && loading); } function setSettingsMsg(text, isError = false) { const node = $('settingsMsg'); node.textContent = text || ''; node.classList.toggle('error', isError); node.classList.toggle('ok', Boolean(text) && !isError); } function toast(message, isError = false) { const node = $('toast'); node.textContent = message; node.classList.toggle('error', isError); node.classList.add('show'); clearTimeout(toastTimer); toastTimer = setTimeout(() => node.classList.remove('show'), 2800); } function fillTtlSelect(select, value) { const wanted = Number(value) || 1; select.textContent = ''; const values = TTL_CHOICES.includes(wanted) ? TTL_CHOICES : TTL_CHOICES.concat(wanted).sort((a, b) => a - b); for (const ttl of values) { const option = document.createElement('option'); option.value = String(ttl); option.textContent = ttl === 1 ? '自动' : ttl + 's'; select.append(option); } select.value = String(wanted); } function makeButton(label, className, onClick) { const btn = document.createElement('button'); btn.type = 'button'; btn.className = className; btn.textContent = label; if (onClick) btn.addEventListener('click', onClick); return btn; } function makeCell(...children) { const cell = document.createElement('td'); cell.append(...children); return cell; } /* ---------------- 视图 ---------------- */ function showView(name) { state.view = name; $('settingsView').classList.toggle('hidden', name !== 'settings'); $('mainView').classList.toggle('hidden', name !== 'main'); } function openPanel() { $('panel').classList.remove('hidden'); $('pill').classList.add('active'); if (!state.token) { fillSettingsInputs(); showView('settings'); $('backBtn').classList.add('hidden'); $('tokenInput').focus(); return; } showView('main'); if (!state.loaded) { state.loaded = true; loadZones().then(loadRecords); } } function closePanel() { $('panel').classList.add('hidden'); $('pill').classList.remove('active'); } function togglePanel() { if ($('panel').classList.contains('hidden')) openPanel(); else closePanel(); } function fillSettingsInputs() { const known = state.zones.some((zone) => zone.id === state.zoneId); $('tokenInput').value = state.token; $('manualZoneId').value = state.zoneId && !known ? state.zoneId : ''; $('manualZoneName').value = state.zoneId && !known ? state.zoneName : ''; $('backBtn').classList.toggle('hidden', !state.token); setSettingsMsg(''); } /* ---------------- 加载 ---------------- */ async function loadZones() { if (!state.token) return; try { state.zones = await getAll('/zones', 50); } catch (err) { state.zones = []; renderZones(); if (!state.zoneId) { toast('读取域名列表失败:' + err.message + '(可在设置里填 Zone ID)', true); } return; } if (!state.zoneId) { state.zoneId = zoneFromUrl() || (state.zones[0] ? state.zones[0].id : ''); const zone = state.zones.find((item) => item.id === state.zoneId); state.zoneName = zone ? zone.name : ''; persistZone(); } else { const zone = state.zones.find((item) => item.id === state.zoneId); if (zone && zone.name !== state.zoneName) { state.zoneName = zone.name; persistZone(); } } renderZones(); } async function loadRecords() { renderZones(); if (!state.zoneId) { state.records = []; render(); return; } state.busy = true; setStatus('加载 DNS 记录…', true); render(); try { state.records = await getAll('/zones/' + state.zoneId + '/dns_records', 100); setStatus(''); } catch (err) { state.records = []; setStatus(''); toast('加载 DNS 记录失败:' + err.message, true); } finally { state.busy = false; render(); } } function renderZones() { const select = $('zoneSelect'); select.textContent = ''; if (state.zones.length === 0) { const option = document.createElement('option'); option.value = state.zoneId || ''; option.textContent = state.zoneName || state.zoneId || '(无法读取域名)'; select.append(option); select.disabled = !state.zoneId; } else { for (const zone of state.zones) { const option = document.createElement('option'); option.value = zone.id; option.textContent = zone.name; select.append(option); } if (state.zoneId && !state.zones.some((zone) => zone.id === state.zoneId)) { const option = document.createElement('option'); option.value = state.zoneId; option.textContent = state.zoneName ? state.zoneName + '(手动)' : state.zoneId + '(手动)'; select.append(option); } select.disabled = false; } select.value = state.zoneId || ''; } /* ---------------- 渲染记录 ---------------- */ function visibleRecords() { const query = state.query.trim().toLowerCase(); return state.records .filter((record) => !state.type || record.type === state.type) .filter((record) => { if (!query) return true; return ( String(record.name).toLowerCase().includes(query) || String(record.content).toLowerCase().includes(query) ); }) .sort((a, b) => a.name.localeCompare(b.name) || a.type.localeCompare(b.type)); } function render() { const tbody = $('tbody'); tbody.textContent = ''; const records = visibleRecords(); const fragment = document.createDocumentFragment(); for (const record of records) fragment.append(buildRow(record)); tbody.append(fragment); const empty = $('empty'); let text = ''; if (!state.zoneId) text = '请先在设置里填写 Zone ID 或选择域名'; else if (!state.busy && state.records.length === 0) text = '这个域名还没有 DNS 记录'; else if (!state.busy && records.length === 0) text = '没有匹配的记录'; empty.textContent = text; empty.classList.toggle('hidden', !text || state.busy); $('counts').textContent = state.zoneId ? '共 ' + state.records.length + ' 条 · 显示 ' + records.length + ' 条' : ''; } function buildRow(record) { if (state.editingId === record.id) return buildEditRow(record); const tr = document.createElement('tr'); tr.dataset.id = record.id; const name = document.createElement('span'); name.className = 'rec-name'; name.textContent = displayName(record.name); name.title = record.name; const typeBadge = document.createElement('span'); typeBadge.className = 'badge type-' + record.type.toLowerCase(); typeBadge.textContent = record.type; const content = document.createElement('span'); content.className = 'rec-content'; content.textContent = record.content; content.title = record.content; const contentCell = makeCell(content); if (record.type === 'MX' && record.priority != null) { const priority = document.createElement('span'); priority.className = 'muted mx-priority'; priority.textContent = '优先级 ' + record.priority; contentCell.append(priority); } let proxyCell; if (!PROXYABLE.has(record.type)) { const dash = document.createElement('span'); dash.className = 'muted'; dash.textContent = '—'; proxyCell = makeCell(dash); } else { const proxy = document.createElement('span'); proxy.className = record.proxied ? 'proxy on' : 'proxy'; proxy.textContent = record.proxied ? '代理' : '仅 DNS'; proxyCell = makeCell(proxy); } const ttl = document.createElement('span'); ttl.textContent = record.ttl === 1 ? '自动' : record.ttl + 's'; const editBtn = makeButton('编辑', 'mini', () => { state.editingId = record.id; state.pendingDeleteId = ''; render(); }); const pending = state.pendingDeleteId === record.id; const deleteBtn = makeButton(pending ? '确认删除' : '删除', pending ? 'mini danger' : 'mini', () => { handleDelete(record, deleteBtn); }); const actions = document.createElement('div'); actions.className = 'row-actions'; if (EDITABLE.has(record.type)) { actions.append(editBtn); } else { const note = document.createElement('span'); note.className = 'muted'; note.textContent = '仅删除'; note.title = '该记录类型请到 Cloudflare 后台编辑'; actions.append(note); } actions.append(deleteBtn); tr.append( makeCell(name), makeCell(typeBadge), contentCell, proxyCell, makeCell(ttl), makeCell(actions) ); return tr; } function buildEditRow(record) { const tr = document.createElement('tr'); tr.className = 'editing'; tr.dataset.id = record.id; const nameInput = document.createElement('input'); nameInput.className = 'cell-input'; nameInput.value = displayName(record.name); nameInput.placeholder = '@ 或子域名'; nameInput.spellcheck = false; const typeBadge = document.createElement('span'); typeBadge.className = 'badge type-' + record.type.toLowerCase(); typeBadge.textContent = record.type; const contentWrap = document.createElement('div'); contentWrap.className = 'content-edit'; const contentInput = document.createElement('input'); contentInput.className = 'cell-input'; contentInput.value = record.content; contentInput.spellcheck = false; contentWrap.append(contentInput); let priorityInput = null; if (record.type === 'MX') { priorityInput = document.createElement('input'); priorityInput.type = 'number'; priorityInput.min = '0'; priorityInput.max = '65535'; priorityInput.className = 'cell-input priority'; priorityInput.value = String(record.priority != null ? record.priority : 10); priorityInput.title = '优先级'; contentWrap.append(priorityInput); } const proxied = document.createElement('input'); proxied.type = 'checkbox'; proxied.checked = Boolean(record.proxied); proxied.disabled = !PROXYABLE.has(record.type); const ttl = document.createElement('select'); ttl.className = 'cell-input ttl'; fillTtlSelect(ttl, record.ttl); const syncTtl = () => { const on = PROXYABLE.has(record.type) && proxied.checked; ttl.disabled = on; if (on) ttl.value = '1'; }; proxied.addEventListener('change', syncTtl); syncTtl(); const actions = document.createElement('div'); actions.className = 'row-actions'; const saveBtn = makeButton('保存', 'mini primary'); const cancelBtn = makeButton('取消', 'mini'); actions.append(saveBtn, cancelBtn); saveBtn.addEventListener('click', async () => { saveBtn.disabled = true; cancelBtn.disabled = true; try { const payload = { name: toFqdn(nameInput.value), content: contentInput.value.trim(), ttl: Number(ttl.value) || 1, }; if (!payload.content) throw new Error('内容不能为空'); if (record.type === 'MX') payload.priority = Number(priorityInput.value || 0); if (PROXYABLE.has(record.type)) { payload.proxied = proxied.checked; if (proxied.checked) payload.ttl = 1; } await cf('/zones/' + state.zoneId + '/dns_records/' + record.id, { method: 'PATCH', body: payload, }); toast('已保存'); state.editingId = ''; await loadRecords(); } catch (err) { toast(err.message, true); saveBtn.disabled = false; cancelBtn.disabled = false; } }); cancelBtn.addEventListener('click', () => { state.editingId = ''; render(); }); tr.append( makeCell(nameInput), makeCell(typeBadge), makeCell(contentWrap), makeCell(proxied), makeCell(ttl), makeCell(actions) ); return tr; } /* ---------------- 操作 ---------------- */ async function handleDelete(record, button) { if (state.pendingDeleteId !== record.id) { state.pendingDeleteId = record.id; clearTimeout(deleteTimer); button.textContent = '确认删除'; button.classList.add('danger'); deleteTimer = setTimeout(() => { if (state.pendingDeleteId === record.id) { state.pendingDeleteId = ''; button.textContent = '删除'; button.classList.remove('danger'); } }, 3000); return; } state.pendingDeleteId = ''; clearTimeout(deleteTimer); button.disabled = true; try { await cf('/zones/' + state.zoneId + '/dns_records/' + record.id, { method: 'DELETE' }); state.records = state.records.filter((item) => item.id !== record.id); toast('已删除'); render(); } catch (err) { toast(err.message, true); button.disabled = false; button.textContent = '删除'; button.classList.remove('danger'); } } async function handleCreate(event) { event.preventDefault(); if (state.busy) return; const type = $('newType').value; const content = $('newContent').value.trim(); const submitBtn = $('createForm').querySelector('button[type="submit"]'); try { if (!state.zoneId) throw new Error('请先选择域名或填写 Zone ID'); if (!content) throw new Error('内容不能为空'); const payload = { type, name: toFqdn($('newName').value), content, ttl: Number($('newTtl').value) || 1, }; if (type === 'MX') payload.priority = Number($('newPriority').value || 0); if (PROXYABLE.has(type)) { payload.proxied = $('newProxied').checked; if (payload.proxied) payload.ttl = 1; } submitBtn.disabled = true; state.busy = true; setStatus('正在创建记录…', true); await cf('/zones/' + state.zoneId + '/dns_records', { method: 'POST', body: payload }); toast('已创建'); $('newName').value = ''; $('newContent').value = ''; $('newContent').focus(); await loadRecords(); } catch (err) { toast(err.message, true); state.busy = false; setStatus(''); render(); } finally { submitBtn.disabled = false; } } function syncCreateFields() { const type = $('newType').value; const proxyable = PROXYABLE.has(type); const proxyOn = proxyable && $('newProxied').checked; $('newProxiedWrap').classList.toggle('hidden', !proxyable); $('newProxied').disabled = !proxyable; $('newPriorityWrap').classList.toggle('hidden', type !== 'MX'); $('newTtl').disabled = proxyOn; if (proxyOn) $('newTtl').value = '1'; $('newContent').placeholder = PLACEHOLDERS[type] || '内容'; } async function handleSaveSettings() { const token = $('tokenInput').value.trim(); const manualId = $('manualZoneId').value.trim(); const manualName = $('manualZoneName').value.trim(); const button = $('saveSettings'); if (!token) { setSettingsMsg('请输入 API 令牌', true); return; } if (manualId && !/^[0-9a-f]{32}$/i.test(manualId)) { setSettingsMsg('Zone ID 格式不对:应为 32 位十六进制字符串', true); return; } button.disabled = true; setSettingsMsg('验证中…'); try { const data = await cf('/user/tokens/verify', { token }); const status = data.result && data.result.status; state.token = token; GM_setValue('cfToken', token); if (manualId) { state.zoneId = manualId; state.zoneName = manualName; persistZone(); } setSettingsMsg('令牌有效' + (status ? '(' + status + ')' : '')); state.loaded = true; showView('main'); await loadZones(); await loadRecords(); if (!state.zoneId) { toast('还没有选择域名:可在设置里填写 Zone ID', true); } } catch (err) { setSettingsMsg(err.message, true); } finally { button.disabled = false; } } /* ---------------- 事件 ---------------- */ function bindEvents() { $('pill').addEventListener('click', togglePanel); $('closeBtn').addEventListener('click', closePanel); $('refreshBtn').addEventListener('click', async () => { if (!state.token) { fillSettingsInputs(); showView('settings'); return; } await loadZones(); await loadRecords(); }); $('settingsBtn').addEventListener('click', () => { fillSettingsInputs(); showView('settings'); }); $('backBtn').addEventListener('click', () => { if (state.token) showView('main'); }); $('toggleToken').addEventListener('click', () => { const input = $('tokenInput'); const visible = input.type === 'text'; input.type = visible ? 'password' : 'text'; $('toggleToken').textContent = visible ? '显示' : '隐藏'; }); $('saveSettings').addEventListener('click', handleSaveSettings); $('tokenInput').addEventListener('keydown', (event) => { if (event.key === 'Enter') { event.preventDefault(); handleSaveSettings(); } }); $('zoneSelect').addEventListener('change', async (event) => { state.zoneId = event.target.value; const zone = state.zones.find((item) => item.id === state.zoneId); state.zoneName = zone ? zone.name : ''; state.editingId = ''; persistZone(); await loadRecords(); }); $('searchInput').addEventListener('input', (event) => { const value = event.target.value; clearTimeout(searchTimer); searchTimer = setTimeout(() => { state.query = value; render(); }, 120); }); $('chips').addEventListener('click', (event) => { const button = event.target.closest('button[data-type]'); if (!button) return; state.type = button.dataset.type; for (const chip of $('chips').querySelectorAll('.chip')) { chip.classList.toggle('on', chip === button); } render(); }); $('addBtn').addEventListener('click', () => { const form = $('createForm'); const show = form.classList.contains('hidden'); form.classList.toggle('hidden', !show); $('addBtn').classList.toggle('active', show); if (show) $('newName').focus(); }); $('cancelCreate').addEventListener('click', () => { $('createForm').classList.add('hidden'); $('addBtn').classList.remove('active'); }); $('newType').addEventListener('change', syncCreateFields); $('newProxied').addEventListener('change', syncCreateFields); $('createForm').addEventListener('submit', handleCreate); $('panel').addEventListener('keydown', (event) => { if (event.key === 'Escape') { if (!$('createForm').classList.contains('hidden')) { $('createForm').classList.add('hidden'); $('addBtn').classList.remove('active'); } else if (state.editingId) { state.editingId = ''; render(); } else if (state.view === 'settings' && state.token) { showView('main'); } else { closePanel(); } event.stopPropagation(); return; } event.stopPropagation(); }); document.addEventListener('keydown', (event) => { if (event.altKey && event.shiftKey && (event.key === 'd' || event.key === 'D')) { event.preventDefault(); if (!isSiteEnabled()) { setSiteEnabled(true); showHost(); openPanel(); } else { togglePanel(); } } }); } if (typeof GM_registerMenuCommand === 'function') { GM_registerMenuCommand('Cloudflare DNS:启用/关闭此网站悬浮窗', () => { const next = !isSiteEnabled(); setSiteEnabled(next); if (next) { showHost(); openPanel(); } else { hideHost(); } }); } fillTtlSelect($('newTtl'), 1); bindEvents(); render(); })();
权限:Zone → DNS → Edit(区域 → DNS → 编辑;必须,不是「DNS 设置」);Zone → Zone → Read(区域 → 读取;可选,用于列出/切换域名)。没有 Zone Read 时,令牌仍能增删改记录;在下面手动填 Zone ID 即可。创建 API 令牌 ↗
Zone → DNS → Edit
Zone → Zone → Read
令牌只保存在本机油猴脚本存储中,请求直连 api.cloudflare.com。项目主页:GitHub