套壳油猴的广告拦截脚本

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

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

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

QingJ © 2025

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