无法弄清楚为什么此代码不编辑 FB 页面中的“href”属性

问题描述

我想知道为什么这段代码不编辑 facebook href 属性

我很确定它应该有效。

我在控制台 Error: Promised response from onMessage listener went out of scope 中出错

代码

// ==UserScript==
// @name         facebook anti tracking URL
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  remove FB tracking
// @author       MévatlavéKraspek
// @match        https://www.facebook.com/*
// @grant        none
// ==/UserScript==


(function() {
    'use strict';
    for (let a of document.querySelectorAll('a')) {
        try {
            var old_url = a.getAttribute('href');
            if (old_url.match(/l\.facebook/)) {
                var myRegexp = /.*l\.facebook\.com\/l\.PHP\?u=(.*)\%3Ffbclid.*/;
                var match = myRegexp.exec(old_url);
                var n = decodeURIComponent(match[1]);
                a.setAttribute('href',n);
            }
        } catch(e) {
            true;
        }
    }

})();

解决方法

我认为您有一个分号导致了问题。

(function() {
    'use strict';
    for (let a of document.querySelectorAll('a')) {
        try {
            var old_url = a.getAttribute('href');
            if (old_url.match(/l\.facebook/)) {
                var myRegexp = /.*l\.facebook\.com\/l\.php\?u=(.*)\%3Ffbclid.*/;
                var match = myRegexp.exec(old_url);
                var n = decodeURIComponent(match[1]);
                a.setAttribute('href',n);
            }
        } catch(e) {
            true;
        };  // <---- remove this semi-colon
    }

})();

我在 facebook.com(在开发控制台中)运行了以下内容,并且成功了:

 for (let a of document.querySelectorAll('a')) {
            try {
                var old_url = a.getAttribute('href');
                console.log(old_url);
            } catch(e) {
                true;
            }
        }

由于此代码运行,这可能意味着问题与您的正则表达式有关。