套壳油猴的广告拦截脚本

将 ABP 中的元素隐藏规则转换为 CSS 使用

当前为 2022-10-05 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name AdBlock Script for WebView
  3. // @name:zh-CN 套壳油猴的广告拦截脚本
  4. // @author Lemon399
  5. // @version 2.1.3
  6. // @description Parse ABP Cosmetic rules to CSS and apply it.
  7. // @description:zh-CN 将 ABP 中的元素隐藏规则转换为 CSS 使用
  8. // @require https://gf.qytechs.cn/scripts/452263-extended-css/code/extended-css.js?version=1099366
  9. // @match *://*/*
  10. // @resource jiekouAD https://code.gitlink.org.cn/damengzhu/banad/raw/branch/main/jiekouAD.txt
  11. // @resource abpmerge https://code.gitlink.org.cn/damengzhu/abpmerge/raw/branch/main/abpmerge.txt
  12. // @run-at document-start
  13. // @grant unsafeWindow
  14. // @grant GM_getValue
  15. // @grant GM_deleteValue
  16. // @grant GM_setValue
  17. // @grant GM_registerMenuCommand
  18. // @grant GM_unregisterMenuCommand
  19. // @grant GM_xmlhttpRequest
  20. // @grant GM_getResourceText
  21. // @grant GM_addStyle
  22. // @namespace https://lemon399-bitbucket-io.vercel.app/
  23. // @source https://gitee.com/lemon399/tampermonkey-cli/tree/master/projects/abp_parse
  24. // @connect code.gitlink.org.cn
  25. // @copyright GPL-3.0
  26. // @license GPL-3.0
  27. // @history 2.0.1 兼容 Tampermonkey 4.18,代码兼容改为 ES6
  28. // @history 2.0.2 修复多个 iframe 首次执行重复下载规则,改进清空功能
  29. // @history 2.0.3 继续改进清空功能
  30. // @history 2.1.0 @resource 内置规则,兼容 X 和 Via
  31. // @history 2.1.1 兼容 MDM
  32. // @history 2.1.2 兼容 脚本猫
  33. // @history 2.1.3 兼容 B 仔
  34. // ==/UserScript==
  35.  
  36. (function (tm, ExtendedCss) {
  37. "use strict";
  38.  
  39. function _interopDefaultLegacy(e) {
  40. return e && typeof e === "object" && "default" in e ? e : { default: e };
  41. }
  42.  
  43. var ExtendedCss__default = /*#__PURE__*/ _interopDefaultLegacy(ExtendedCss);
  44.  
  45. function __awaiter(thisArg, _arguments, P, generator) {
  46. function adopt(value) {
  47. return value instanceof P
  48. ? value
  49. : new P(function (resolve) {
  50. resolve(value);
  51. });
  52. }
  53. return new (P || (P = Promise))(function (resolve, reject) {
  54. function fulfilled(value) {
  55. try {
  56. step(generator.next(value));
  57. } catch (e) {
  58. reject(e);
  59. }
  60. }
  61. function rejected(value) {
  62. try {
  63. step(generator["throw"](value));
  64. } catch (e) {
  65. reject(e);
  66. }
  67. }
  68. function step(result) {
  69. result.done
  70. ? resolve(result.value)
  71. : adopt(result.value).then(fulfilled, rejected);
  72. }
  73. step((generator = generator.apply(thisArg, _arguments || [])).next());
  74. });
  75. }
  76.  
  77. const onlineRules = [
  78. "https://code.gitlink.org.cn/damengzhu/banad/raw/branch/main/jiekouAD.txt",
  79. "https://code.gitlink.org.cn/damengzhu/abpmerge/raw/branch/main/abpmerge.txt",
  80. ],
  81. defaultRules = `
  82. ! 没有 ## #@# #?# #@?#
  83. ! #$# #@$# #$?# #@$?# 的行和
  84. ! 开头为 ! 的行会忽略
  85. !
  86. ! 由于语法限制,内置规则中
  87. ! 一个反斜杠需要改成两个,像这样 \\
  88. !
  89. ! 若要修改地址,请注意同步修改
  90. ! 头部的 @connect @resource
  91.  
  92. baidu.com##.ec_wise_ad
  93.  
  94. `;
  95.  
  96. function runOnce(key, func, ...params) {
  97. if (key in unsafeWindow) return;
  98. unsafeWindow[key] = true;
  99. func === null || func === void 0 ? void 0 : func.apply(this, params);
  100. }
  101. function isValidConfig(obj, ref) {
  102. let valid = typeof obj == "object";
  103. Object.getOwnPropertyNames(obj).forEach((k) => {
  104. if (!ref.hasOwnProperty(k)) valid = false;
  105. });
  106. return valid;
  107. }
  108. function sleep(time) {
  109. return new Promise((resolve) => setTimeout(resolve, time));
  110. }
  111. function runNeed(condition, fn, option, ...args) {
  112. let ok = false;
  113. const defaultOption = {
  114. count: 20,
  115. delay: 200,
  116. failFn: () => null,
  117. };
  118. if (isValidConfig(option, defaultOption))
  119. Object.assign(defaultOption, option);
  120. new Promise((resolve, reject) =>
  121. __awaiter(this, void 0, void 0, function* () {
  122. for (let c = 0; !ok && c < defaultOption.count; c++) {
  123. yield sleep(defaultOption.delay);
  124. ok = condition.call(null, c + 1);
  125. }
  126. ok ? resolve() : reject();
  127. })
  128. ).then(fn.bind(null, ...args), defaultOption.failFn);
  129. }
  130. function getName(path) {
  131. const reer = /\/([^\/]+)$/.exec(path);
  132. return reer ? reer[1] : null;
  133. }
  134. function getEtag(header) {
  135. const reer = /etag: \"(\w+)\"/.exec(header);
  136. const reerVia = /Etag: \[\"(\w+)\"\]/.exec(header);
  137. return reer ? reer[1] : reerVia ? reerVia[1] : null;
  138. }
  139. function getDay(date) {
  140. const reer = /\/(\d{1,2}) /.exec(date);
  141. return reer ? parseInt(reer[1]) : 0;
  142. }
  143. function makeRuleBox() {
  144. return {
  145. black: [],
  146. white: [],
  147. apply: "",
  148. };
  149. }
  150. function domainChecker(domains) {
  151. const results = [],
  152. hasTLD = /\.+?[\w-]+$/,
  153. urlSuffix = hasTLD.exec(location.hostname);
  154. let invert = false,
  155. result = false,
  156. mostMatch = {
  157. long: 0,
  158. result: undefined,
  159. };
  160. domains.forEach((domain) => {
  161. if (domain.endsWith(".*") && Array.isArray(urlSuffix)) {
  162. domain = domain.replace(".*", urlSuffix[0]);
  163. }
  164. if (domain.startsWith("~")) {
  165. invert = true;
  166. domain = domain.slice(1);
  167. } else invert = false;
  168. result = location.hostname.endsWith(domain);
  169. results.push(result !== invert);
  170. if (result) {
  171. if (domain.length > mostMatch.long) {
  172. mostMatch = {
  173. long: domain.length,
  174. result: result !== invert,
  175. };
  176. }
  177. }
  178. });
  179. return mostMatch.long > 0 ? mostMatch.result : results.includes(true);
  180. }
  181. function ruleChecker(matches) {
  182. const index = matches.findIndex((i) => i !== null);
  183. if (
  184. index >= 0 &&
  185. (!matches[index][1] || domainChecker(matches[index][1].split(",")))
  186. ) {
  187. return [index % 2 == 0, Math.floor(index / 2), matches[index].pop()];
  188. }
  189. }
  190. function extraChecker(sel) {
  191. const unsupported = [
  192. ":matches-path(",
  193. ":min-text-length(",
  194. ":watch-attr(",
  195. ":style(",
  196. ];
  197. let pass = true;
  198. unsupported.forEach((cls) => {
  199. if (sel.indexOf(cls) >= 0) pass = false;
  200. });
  201. return pass;
  202. }
  203. function ruleSpliter(rule) {
  204. const result = ruleChecker([
  205. rule.match(
  206. /^(~?[\w-]+\.([\w-]+|\*)(,~?[\w-]+\.([\w-]+|\*))*)?##([^\s^+].*)/
  207. ),
  208. rule.match(
  209. /^(~?[\w-]+\.([\w-]+|\*)(,~?[\w-]+\.([\w-]+|\*))*)?#@#([^\s^+].*)/
  210. ),
  211. rule.match(
  212. /^(~?[\w-]+\.([\w-]+|\*)(,~?[\w-]+\.([\w-]+|\*))*)?#\?#([^\s^+].*)/
  213. ),
  214. rule.match(
  215. /^(~?[\w-]+\.([\w-]+|\*)(,~?[\w-]+\.([\w-]+|\*))*)?#@\?#([^\s^+].*)/
  216. ),
  217. rule.match(
  218. /^(~?[\w-]+\.([\w-]+|\*)(,~?[\w-]+\.([\w-]+|\*))*)?#\$#([^\s^+].*)/
  219. ),
  220. rule.match(
  221. /^(~?[\w-]+\.([\w-]+|\*)(,~?[\w-]+\.([\w-]+|\*))*)?#@\$#([^\s^+].*)/
  222. ),
  223. rule.match(
  224. /^(~?[\w-]+\.([\w-]+|\*)(,~?[\w-]+\.([\w-]+|\*))*)?#\$\?#([^\s^+].*)/
  225. ),
  226. rule.match(
  227. /^(~?[\w-]+\.([\w-]+|\*)(,~?[\w-]+\.([\w-]+|\*))*)?#@\$\?#([^\s^+].*)/
  228. ),
  229. ]);
  230. if (result && result[2] && extraChecker(result[2])) {
  231. return {
  232. black: result[0],
  233. type: result[1],
  234. sel: result[2],
  235. };
  236. }
  237. }
  238.  
  239. if (typeof unsafeWindow !== "object") {
  240. unsafeWindow = window;
  241. }
  242. const selectors = makeRuleBox(),
  243. extSelectors = makeRuleBox(),
  244. styles = makeRuleBox(),
  245. extStyles = makeRuleBox(),
  246. values = {
  247. get black() {
  248. const v = tm.GM_getValue("ajs_disabled_domains", "");
  249. return typeof v == "string" ? v : "";
  250. },
  251. set black(v) {
  252. v === null
  253. ? tm.GM_deleteValue("ajs_disabled_domains")
  254. : tm.GM_setValue("ajs_disabled_domains", v);
  255. },
  256. get rules() {
  257. let v;
  258. try {
  259. v = tm.GM_getValue("ajs_saved_abprules", "{}");
  260. } catch (error) {
  261. v = "{}";
  262. }
  263. return typeof v == "string" ? JSON.parse(v) : {};
  264. },
  265. set rules(v) {
  266. try {
  267. v === null
  268. ? tm.GM_deleteValue("ajs_saved_abprules")
  269. : tm.GM_setValue("ajs_saved_abprules", JSON.stringify(v));
  270. } catch (error) {
  271. tm.GM_deleteValue("ajs_saved_abprules");
  272. }
  273. },
  274. get time() {
  275. const v = tm.GM_getValue("ajs_rules_ver", "0/0/0 0:0:0");
  276. return typeof v == "string" ? v : "0/0/0 0:0:0";
  277. },
  278. set time(v) {
  279. v === null
  280. ? tm.GM_deleteValue("ajs_rules_ver")
  281. : tm.GM_setValue("ajs_rules_ver", v);
  282. },
  283. get etags() {
  284. const v = tm.GM_getValue("ajs_rules_etags", "{}");
  285. return typeof v == "string" ? JSON.parse(v) : {};
  286. },
  287. set etags(v) {
  288. v === null
  289. ? tm.GM_deleteValue("ajs_rules_etags")
  290. : tm.GM_setValue("ajs_rules_etags", JSON.stringify(v));
  291. },
  292. },
  293. data = {
  294. disabled: false,
  295. updating: false,
  296. receivedRules: "",
  297. allRules: "",
  298. genericStyle: document.createElement("style"),
  299. presetCss:
  300. " {display: none !important;width: 0 !important;height: 0 !important;} ",
  301. supportedCount: 0,
  302. appliedCount: 0,
  303. isFrame: unsafeWindow.self !== unsafeWindow.top,
  304. isClean: false,
  305. mutex: "__lemon__abp__parser__$__",
  306. debug: false,
  307. timeout: 5000,
  308. },
  309. menus = {
  310. disable: {
  311. id: undefined,
  312. get text() {
  313. return data.disabled ? "在此网站启用拦截" : "在此网站禁用拦截";
  314. },
  315. },
  316. update: {
  317. id: undefined,
  318. get text() {
  319. const time = values.time;
  320. return data.updating
  321. ? "正在更新..."
  322. : `点击更新: ${time.slice(0, 1) === "0" ? "未知时间" : time}`;
  323. },
  324. },
  325. count: {
  326. id: undefined,
  327. get text() {
  328. return data.isClean
  329. ? "已清空,点击刷新重新加载规则"
  330. : `点击清空: ${data.appliedCount} / ${data.supportedCount} / ${
  331. data.allRules.split("\n").length
  332. }`;
  333. },
  334. },
  335. };
  336. function gmMenu(name, cb) {
  337. if (
  338. typeof tm.GM_registerMenuCommand !== "function" ||
  339. typeof tm.GM_unregisterMenuCommand !== "function" ||
  340. data.isFrame
  341. )
  342. return false;
  343. const id = menus[name].id;
  344. if (typeof id !== "undefined") {
  345. tm.GM_unregisterMenuCommand(id);
  346. menus[name].id = undefined;
  347. }
  348. if (typeof cb == "function") {
  349. menus[name].id = tm.GM_registerMenuCommand(menus[name].text, cb);
  350. }
  351. return typeof menus[name].id !== "undefined";
  352. }
  353. function promiseXhr(details) {
  354. return __awaiter(this, void 0, void 0, function* () {
  355. let loaded = false;
  356. try {
  357. return yield new Promise((resolve, reject) => {
  358. tm.GM_xmlhttpRequest(
  359. Object.assign(
  360. {
  361. onload(e) {
  362. loaded = true;
  363. resolve(e);
  364. },
  365. onabort: reject.bind(null, "abort"),
  366. onerror: reject.bind(null, "error"),
  367. ontimeout: reject.bind(null, "timeout"),
  368. onreadystatechange(e_1) {
  369. // X 浏览器超时中断
  370. if (e_1.readyState === 4) {
  371. setTimeout(() => {
  372. if (!loaded) reject("X timeout");
  373. }, 300);
  374. }
  375. // Via 浏览器超时中断,不给成功状态...
  376. if (e_1.readyState === 3) {
  377. setTimeout(() => {
  378. if (!loaded) reject("Via timeout");
  379. }, data.timeout);
  380. }
  381. },
  382. timeout: data.timeout,
  383. },
  384. details
  385. )
  386. );
  387. });
  388. } catch (r) {}
  389. });
  390. }
  391. function storeRule(name, resp) {
  392. const savedRules = values.rules,
  393. savedEtags = values.etags;
  394. if (resp.responseHeaders) {
  395. const etag = getEtag(resp.responseHeaders);
  396. if (etag) {
  397. savedEtags[name] = etag;
  398. values.etags = savedEtags;
  399. }
  400. }
  401. if (resp.responseText) {
  402. savedRules[name] = resp.responseText;
  403. values.rules = savedRules;
  404. }
  405. }
  406. function fetchRuleBody(name, url) {
  407. return __awaiter(this, void 0, void 0, function* () {
  408. const getResp = yield promiseXhr({
  409. method: "GET",
  410. responseType: "text",
  411. url: url,
  412. });
  413. if (getResp) {
  414. storeRule(name, getResp);
  415. return true;
  416. } else return false;
  417. });
  418. }
  419. function fetchRule(url) {
  420. var _a;
  421. const name =
  422. (_a = getName(url)) !== null && _a !== void 0
  423. ? _a
  424. : `${url.length}.${url.slice(-5)}`;
  425. return new Promise((resolve, reject) =>
  426. __awaiter(this, void 0, void 0, function* () {
  427. var _b, _c;
  428. if (!name) reject();
  429. const headResp = yield promiseXhr({
  430. method: "HEAD",
  431. responseType: "text",
  432. url: url,
  433. });
  434. if (!headResp) {
  435. reject();
  436. } else {
  437. if (headResp.responseText) {
  438. storeRule(name, headResp);
  439. resolve();
  440. } else {
  441. const etag = getEtag(
  442. typeof headResp.responseHeaders == "string"
  443. ? headResp.responseHeaders
  444. : (_c = (_b = headResp).getAllResponseHeaders) === null ||
  445. _c === void 0
  446. ? void 0
  447. : _c.call(_b)
  448. ),
  449. savedEtags = values.etags;
  450. if (etag) {
  451. if (etag !== savedEtags[name]) {
  452. (yield fetchRuleBody(name, url)) ? resolve() : reject();
  453. } else reject();
  454. } else {
  455. (yield fetchRuleBody(name, url)) ? resolve() : reject();
  456. }
  457. }
  458. }
  459. })
  460. );
  461. }
  462. function fetchRules() {
  463. return __awaiter(this, void 0, void 0, function* () {
  464. data.updating = true;
  465. gmMenu("update", () => undefined);
  466. for (const url of onlineRules) yield fetchRule(url).catch((r) => {});
  467. values.time = new Date().toLocaleString("zh-CN");
  468. gmMenu("count", cleanRules);
  469. initRules();
  470. });
  471. }
  472. function performUpdate(force) {
  473. if (force) {
  474. return fetchRules();
  475. } else {
  476. return getDay(values.time) !== new Date().getDate()
  477. ? fetchRules()
  478. : Promise.resolve();
  479. }
  480. }
  481. function switchDisabledStat() {
  482. const disaList = values.black.split(","),
  483. disaResult = disaList.includes(location.hostname);
  484. data.disabled = !disaResult;
  485. if (data.disabled) {
  486. disaList.push(location.hostname);
  487. } else {
  488. disaList.splice(disaList.indexOf(location.hostname), 1);
  489. }
  490. values.black = disaList.join(",");
  491. gmMenu("disable", switchDisabledStat);
  492. }
  493. function checkDisableStat() {
  494. const disaResult = values.black.split(",").includes(location.hostname);
  495. data.disabled = disaResult;
  496. gmMenu("disable", switchDisabledStat);
  497. return disaResult;
  498. }
  499. function initRules() {
  500. const abpRules = values.rules;
  501. if (typeof tm.GM_getResourceText == "function") {
  502. onlineRules.forEach((url) => {
  503. const ruleName = getName(url),
  504. resName = ruleName.split(".")[0],
  505. resRule = tm.GM_getResourceText(resName);
  506. if (resRule && !abpRules[ruleName]) abpRules[ruleName] = resRule;
  507. });
  508. }
  509. const abpKeys = Object.keys(abpRules);
  510. abpKeys.forEach((name) => {
  511. data.receivedRules += "\n" + abpRules[name] + "\n";
  512. });
  513. data.allRules = defaultRules + data.receivedRules;
  514. if (abpKeys.length !== 0) {
  515. data.updating = false;
  516. gmMenu("update", () =>
  517. __awaiter(this, void 0, void 0, function* () {
  518. yield performUpdate(true);
  519. location.reload();
  520. })
  521. );
  522. }
  523. return data.receivedRules.length;
  524. }
  525. function styleApply() {
  526. const css =
  527. styles.apply +
  528. (selectors.apply.length > 0 ? selectors.apply + data.presetCss : ""),
  529. ecss =
  530. extStyles.apply +
  531. (extSelectors.apply.length > 0
  532. ? extSelectors.apply + data.presetCss
  533. : "");
  534. if (css.length > 0) {
  535. if (typeof tm.GM_addStyle == "function") {
  536. tm.GM_addStyle(css);
  537. } else {
  538. runNeed(
  539. () => !!document.documentElement,
  540. () => {
  541. data.genericStyle.textContent = css;
  542. document.documentElement.appendChild(data.genericStyle);
  543. }
  544. );
  545. }
  546. }
  547. if (ecss.length > 0)
  548. new ExtendedCss__default.default({ styleSheet: ecss }).apply();
  549. }
  550. function cleanRules() {
  551. if (confirm("是否清空存储规则 ?")) {
  552. values.rules = {};
  553. values.time = "0/0/0 0:0:0";
  554. values.etags = {};
  555. data.appliedCount = 0;
  556. data.supportedCount = 0;
  557. data.allRules = "";
  558. data.isClean = true;
  559. gmMenu("update");
  560. gmMenu("count", () => location.reload());
  561. }
  562. }
  563. function parseRules() {
  564. [selectors, extSelectors].forEach((obj) => {
  565. obj.black
  566. .filter((v) => !obj.white.includes(v))
  567. .forEach((sel) => {
  568. obj.apply += `${obj.apply.length == 0 ? "" : ","}${sel}`;
  569. data.appliedCount++;
  570. });
  571. });
  572. [styles, extStyles].forEach((obj) => {
  573. obj.black
  574. .filter((v) => !obj.white.includes(v))
  575. .forEach((sel) => {
  576. obj.apply += ` ${sel}`;
  577. data.appliedCount++;
  578. });
  579. });
  580. gmMenu("count", cleanRules);
  581. styleApply();
  582. }
  583. function main() {
  584. return __awaiter(this, void 0, void 0, function* () {
  585. if (checkDisableStat() || (initRules() === 0 && data.isFrame)) return;
  586. if (data.receivedRules.length === 0) yield performUpdate(true);
  587. data.allRules.split("\n").forEach((rule) => {
  588. const ruleObj = ruleSpliter(rule);
  589. let arr = "";
  590. if (typeof ruleObj !== "undefined") {
  591. arr = ruleObj.black ? "black" : "white";
  592. switch (ruleObj.type) {
  593. case 0:
  594. selectors[arr].push(ruleObj.sel);
  595. break;
  596. case 1:
  597. extSelectors[arr].push(ruleObj.sel);
  598. break;
  599. case 2:
  600. styles[arr].push(ruleObj.sel);
  601. break;
  602. case 3:
  603. extStyles[arr].push(ruleObj.sel);
  604. break;
  605. }
  606. data.supportedCount++;
  607. }
  608. });
  609. parseRules();
  610. performUpdate(false);
  611. });
  612. }
  613. runOnce(data.mutex, main);
  614. })(
  615. {
  616. unsafeWindow,
  617. GM_getValue,
  618. GM_deleteValue,
  619. GM_setValue,
  620. GM_registerMenuCommand,
  621. GM_unregisterMenuCommand,
  622. GM_xmlhttpRequest,
  623. GM_getResourceText,
  624. GM_addStyle,
  625. },
  626. ExtendedCss
  627. );

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址