Repository: mgziminsky/FacebookTrackingRemoval Branch: master Commit: 9ca9fd6d1987 Files: 60 Total size: 161.5 KB Directory structure: gitextract_tbc1b974/ ├── .gitattributes ├── .github/ │ ├── ISSUE_TEMPLATE/ │ │ ├── ad-blocking-support.md │ │ ├── bug_report.md │ │ └── feature_request.md │ ├── dependabot.yml │ └── workflows/ │ ├── codeql.yml │ └── mirror-gitlab.yml ├── .gitignore ├── .gitlab-ci.yml ├── .gitmodules ├── .vscode/ │ ├── extensions.json │ ├── html.html-data.json │ ├── launch.json │ └── settings.json ├── CHANGELOG ├── LICENSE ├── README.md ├── _locales/ │ ├── en/ │ │ └── messages.json │ └── fr/ │ └── messages.json ├── biome.json ├── data/ │ ├── click_whitelist/ │ │ ├── elements │ │ ├── roles │ │ └── selectors │ ├── declarativeNetRequest.json │ ├── hide_rules/ │ │ ├── article_wrapper │ │ ├── content │ │ ├── pending │ │ ├── sponsored/ │ │ │ ├── patterns │ │ │ ├── selectors │ │ │ └── texts │ │ ├── suggested/ │ │ │ ├── patterns │ │ │ ├── selectors │ │ │ └── texts │ │ ├── suggestions_smart │ │ └── unconditional │ └── param_cleaning/ │ ├── params │ ├── prefix_patterns │ └── values ├── jsconfig.json ├── manifest.json ├── package.sh └── src/ ├── background/ │ ├── background.js │ └── webrequest.js ├── common.js ├── config.js ├── consts.js ├── content_script/ │ ├── app.css │ ├── app.js │ ├── canvas_fingerprint.js │ ├── cleaning.js │ ├── content_script.js │ └── dom.js ├── i18n.js ├── options/ │ ├── options.css │ ├── options.html │ ├── options.js │ └── theme.css ├── rules_sync.js ├── types.d.ts └── util.js ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitattributes ================================================ # Auto detect text files and perform LF normalization * text=auto # Custom for Visual Studio *.cs diff=csharp # Standard to msysgit *.doc diff=astextplain *.DOC diff=astextplain *.docx diff=astextplain *.DOCX diff=astextplain *.dot diff=astextplain *.DOT diff=astextplain *.pdf diff=astextplain *.PDF diff=astextplain *.rtf diff=astextplain *.RTF diff=astextplain ================================================ FILE: .github/ISSUE_TEMPLATE/ad-blocking-support.md ================================================ --- name: Ad blocking support about: For if you're seeing ads. Request help with manually identifying ad CSS selectors title: '' labels: Ad Blocking assignees: '' --- ## Please provide a screenshot of the ad or content that you think should be blocked. No support will be given until one is provided. Ads are blocked based on a combination CSS selectors and text strings or regex patterns. Typically, all you need to provide is an example of the ad in a screenshot and I will be able to verify and add a rule to the list. If possible, it would also help if you are able to add a custom rule under the advanced options and provide a screenshot verifying it works. If unsure, a reliable, but slow, selector to use would be `div,span,a` Facebook doesn't give every person the same version of code that displays the site. They do this for various reasons, such as testing new features on just some users before rolling them out to everyone, or for some content that is only available in certain countries. Because of this, what works for me, may not work for you. Since I am only able to work with what Facebook gives me personally, there is no way for me to investigate other users' issues that aren't also present for me. It's possible that if you wait for a little while, I might start getting the same version as you, and will be able to fix the problem on my own. Otherwise, the only way to find the solution is if you do so yourself. ================================================ FILE: .github/ISSUE_TEMPLATE/bug_report.md ================================================ --- name: Bug Report about: Report broken functionality or other problems with the extension title: '' labels: bug assignees: '' --- # Requests about ads not being hidden will be closed without response. Follow the instructions in the "Ad blocking support" template for that. **Describe the bug** A clear and concise description of what the bug is. **To Reproduce** Steps to reproduce the behavior: 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' 4. See error **Expected behavior** A clear and concise description of what you expected to happen. **Screenshots** If applicable, add screenshots to help explain your problem. **Please provide the following information:** - Device: [e.g. Desktop, iPhone6, etc.] - OS: [e.g. Windows, Linux, iOS] - Browser [e.g. firefox, chrome] - Extension Version [e.g. 1.6.1] - Extension Options **Additional context** Add any other context about the problem here. ================================================ FILE: .github/ISSUE_TEMPLATE/feature_request.md ================================================ --- name: Feature Request about: Suggest an idea for this project title: '' labels: enhancement assignees: '' --- **Is your feature request related to a problem? Please describe.** A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] **Describe the solution you'd like** A clear and concise description of what you want to happen. **Describe alternatives you've considered** A clear and concise description of any alternative solutions or features you've considered. **Additional context** Add any other context or screenshots about the feature request here. ================================================ FILE: .github/dependabot.yml ================================================ # Please see the documentation for all configuration options: # https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates version: 2 updates: - package-ecosystem: "github-actions" # See documentation for possible values directory: "/" # Location of package manifests schedule: interval: "weekly" - package-ecosystem: "gitsubmodule" directory: "/" schedule: interval: "weekly" ================================================ FILE: .github/workflows/codeql.yml ================================================ # For most projects, this workflow file will not need changing; you simply need # to commit it to your repository. # # You may wish to alter this file to override the set of languages analyzed, # or to provide custom queries or build logic. # # ******** NOTE ******** # We have attempted to detect the languages in your repository. Please check # the `language` matrix defined below to confirm you have the correct set of # supported CodeQL languages. # name: "CodeQL" on: workflow_dispatch: push: branches: [ master ] paths: [ 'src/**' ] pull_request: # The branches below must be a subset of the branches above branches: [ master ] paths: [ 'src/**' ] jobs: analyze: name: Analyze runs-on: ubuntu-latest permissions: actions: read contents: read security-events: write strategy: fail-fast: false matrix: language: [ 'javascript' ] # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ] # Learn more about CodeQL language support at https://git.io/codeql-language-support steps: - name: Checkout repository uses: actions/checkout@v6 # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL uses: github/codeql-action/init@v4 with: languages: ${{ matrix.language }} # If you wish to specify custom queries, you can do so here or in a config file. # By default, queries listed here will override any specified in a config file. # Prefix the list here with "+" to use these queries and those in the config file. # queries: ./path/to/local/query, your-org/your-repo/queries@main - name: Perform CodeQL Analysis uses: github/codeql-action/analyze@v4 ================================================ FILE: .github/workflows/mirror-gitlab.yml ================================================ name: Mirror to Gitlab on: workflow_dispatch: push: branches: [master] jobs: mirror: name: Mirror runs-on: ubuntu-latest permissions: contents: read steps: - name: Checkout repository uses: actions/checkout@v6 with: fetch-depth: 0 - name: Setup SSH env: GITLAB_PUSH_KEY: ${{ secrets.GITLAB_PUSH_KEY }} run: | mkdir -p ~/.ssh/ chmod 700 ~/.ssh/ echo "$GITLAB_PUSH_KEY" > ~/.ssh/push_key chmod 400 ~/.ssh/push_key - name: Push to Gitlab env: GIT_SSH_COMMAND: ssh -v -i ~/.ssh/push_key -o IdentitiesOnly=yes -o StrictHostKeyChecking=no run: git push --force --prune git@gitlab.com:mgziminsky/FacebookTrackingRemoval.git master refs/tags/* ================================================ FILE: .gitignore ================================================ _metadata/ *.zip browser-polyfill.min.js* webextension-polyfill/package-lock.json ================================================ FILE: .gitlab-ci.yml ================================================ image: alpine:latest pages: stage: deploy script: - mv data public artifacts: paths: - public rules: - if: $CI_COMMIT_REF_NAME == $CI_DEFAULT_BRANCH changes: - data/**/* ================================================ FILE: .gitmodules ================================================ [submodule "webextension-polyfill"] path = webextension-polyfill url = https://github.com/mozilla/webextension-polyfill.git ================================================ FILE: .vscode/extensions.json ================================================ { // See https://go.microsoft.com/fwlink/?LinkId=827846 to learn about workspace recommendations. // Extension identifier format: ${publisher}.${name}. Example: vscode.csharp // List of extensions which should be recommended for users of this workspace. "recommendations": [ "firefox-devtools.vscode-firefox-debug", "biomejs.biome" ], // List of extensions recommended by VS Code that should not be recommended for users of this workspace. "unwantedRecommendations": [] } ================================================ FILE: .vscode/html.html-data.json ================================================ { "version": 1.1, "tags": [ { "name": "fbtr-i18n", "description": "Renders translation string specified by `key` as html", "attributes": [ { "name": "key" } ] } ], "globalAttributes": [ { "name": "data-i18n", "description": "Translation key of which the value will be assigned to the attribute specified by [data-i18n-attr], or [title] if not specified" }, { "name": "data-i18n-attr", "description": "Name of attribute that will be assigned the value of the translation specified in [data-i18n]" }, { "name": "data-i18n-vars", "description": "Values of any variables needed by translation specified by [data-i18n]; Multiple values are separated by ||" } ] } ================================================ FILE: .vscode/launch.json ================================================ { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Launch WebExtension", "type": "firefox", "request": "launch", "reAttach": true, "addonPath": "${workspaceFolder}", "reloadOnChange": { "watch": [ "${workspaceFolder}/manifest.json", "${workspaceFolder}/src/background.js", "${workspaceFolder}/_locales/**/messages.json", ], }, "showConsoleCallLocation": false, "tabFilter": "https://*.facebook.com/*" } ] } ================================================ FILE: .vscode/settings.json ================================================ { "firefox.args": [ "about:debugging#/runtime/this-firefox", "about:addons", "https://www.facebook.com/", ], "html.customData": [ ".vscode/html.html-data.json", ], "licenser.useSingleLineStyle": false, "licenser.license": "GPLv3", "[javascript]": { "editor.codeActionsOnSave": { "source.organizeImports.biome": "explicit" }, }, "[javascript][json][jsonc][typescript]": { "editor.defaultFormatter": "biomejs.biome" }, "files.associations": { "**/FacebookTrackingRemoval/data/**/*": "plaintext" } // "json.schemas": [{ // "url": "https://json.schemastore.org/chrome-manifest.json", // "fileMatch": ["/manifest.json"] // }] } ================================================ FILE: CHANGELOG ================================================ v1.13.0 - New option to detect ads with canvas labels (Default: Enabled) v1.12.0 - Migrate to manifest v3 v1.11.3 - Link cleaning fix for FF115+ v1.11.2 - More svg label handling adjustments v1.11.1 - Fix split text in svg labels v1.11.0 - Refactored project into ES modules - Options changes are applied without a page reload - Existing rules won't be replaced by bundled copies in case of network errors - Fixes and supporting code for marketplace ads v1.10.4 - Fix ad detection. Handle svg/aria trickery. v1.10.3 - Fix mention completion popup - closes #62 v1.10.2 - Fix custom user rules under advanced options v1.10.1 - Fix feed breaking when "Hide method" set to "Remove" v1.10.0.1 - Remove marketplace sponsored - Themed options - Backend code improvements and changes v1.9.3 - Don't block the heartbeat ping. FB disables things when it fails v1.9.2 - Fix some internal links not being cleaned v1.9.1 - Fix rules not updating v1.9.0 - Remove legacy static matching and integrate functionality into content-based matching - Don't strip spaces from text used for content hiding rules - Closes #45 v1.8.10 - Fix some navigation issues with internal link cleaning enabled - closes #44 v1.8.9 - Block additional background tracking and metrics submission - Fix video volume adjustment slider - closes #43 v1.8.8 - Load at document_end again for hiding sidebar sponsored v1.8.7 - Fix automatic page reload on options changes - Fix comment input not clickable, and maybe others. Closes #37 v1.8.6 - French translation provided by gatinhonico v1.8.5 - Internal link cleaning fixes and improvements - Run properly on pages that are loaded in IFrames - Fix processing that should happen at initial page load - Bump min required version to FF 59 v1.8.4 - Fix infinite event recursion caused by links with a nested fbclid v1.8.3 - Use smart detection for Suggested Posts v1.8.2 - Better smart sponsored detection v1.8.1 - Update to work with new FB design - Smarter sponsored post detection - Big performance improvement - Update default style to not break layout v1.8.0.2 - Force refresh rules on upgrade - Improved performance, hopefully by a noticeable amount v1.7.1 - Improved performance v1.7.0 - No more tabs permission - Style changes now happen without reloading the page v1.6.9 - Detect new form of sponsored posts - Improve performace when styling is enabled v1.6.8.1 - Fix minor bug when cleaning link info bubble - Fix fallback rule loading for whitelisted clicks and param cleaning v1.6.7 - Fix extension not working at all when "Fix external links" is disabled - Add more details to log when something is hidden/removed v1.6.6 - Support messenger.com - Closes #27 v1.6.5 - Fixes for parts of messenger page - Closes #26 - Prevent FB from resetting links after they've been cleaned v1.6.4 - Internal code improvements and bug fixes - Moved remaining hard-coded data to hosting to support easier updates without version bumps v1.6.3 - Fix reactions in chat and some breakages caused by internal link cleaning. Closes #25 - Remove some new internal tracking parameters v1.6.2 - Slightly smarter sponsored identification v1.6.1 - Remove fbclid from links - Closes #20 v1.6.0 - New advanced option for custom, user defined ad hiding rules - Block requests to pixel.facebook.com - Per-option reset and various other options enhancements - Load ad hiding rules from web. No more version bumps just for selector changes. v1.5.18 - Fix stickers, gifs, and games in chat. Closes #17 - Fix sponsored post removal deleting everything. Closes #18 v1.5.17 - More clickable fixes v1.5.16 - Fix potential XSS vulnerability (Thanks Bennett from EFF) - Fix a couple more clickables v1.5.15 - Don't hide/remove group management controls; Closes issue #13 - Fix various clickable components; Closes issue #15 - General improvements to internal link cleaning v1.5.14 - Fix regression in user interactions - Minor performace improvements - Remove desktop video cleaning option until I find a solution to the broken videos v1.5.13 - Block ajax tracking requests. Closes issue #10 v1.5.12 - Sync options pages - Fix auto page reload in chrome and FF 60+ - New classes for Sponsored and Suggested posts v1.5.11 - Update to work on FB tor/onion service - Add rel=noreferrer to cleaned links v1.5.10 - Hide "Suggested Shows" - Don't hide emergency broadcasts such as Amber Alerts and highlight them red v1.5.9 - Fix for some links not getting cleaned v1.5.8 - Handle new class of "Sponsored" - Handle additional type of internal link v1.5.7 - Handle new class of "Suggested Posts" v1.5.6 - Fix external links on mobile - Improved mobile video inlining v1.5.5 - Strip __md__ param from internal links - Handle new "SponSsored" posts * FB has been trying to get sneaky with their sponsored posts lately. First by setting the text using CSS, and now misspelled with the extra letter hidden. v1.5.4 - Fix GIFs not playing (issue #4) - Disable styling by default v1.5.3 - Fix Sponsored hiding - Fix Mobile hiding - Include new "Suggested Post" class - Hide suggestions on photo overlay v1.5.2 - Hide "Page Stories You May Like" - Hide "Games You May Like" - Disable hiding "Sponsored Articles" by default. No longer works correctly. v1.5.1 - Hide "Related Articles" and "Popular Across Facebook" v1.5.0 - Remove cross-device sync option. It needed some enhancements, but I didn't feel the feature was useful - Add option to enable/disable the plugin entirely v1.4.3 - Preserve existing element styles v1.4.2 - Ad blocking enabled by default - Improved internal link cleaning v1.4.1 - Option to remove referrer tracking on internal links - Auto refresh Facebook™ pages after changing options - Improved sidebar ad blocking v1.4.0 - Add icon and options page action - Fixes for mobile - Option to sync options across devices [FF 53+] v1.3.9 - Hide "A video you may like" v1.3.8 - Hide "People You May Know" - Use HTML5 details for collapsing posts v1.3.7 - Hide sponsored ads panel - Fix non-link click tracking prevention - Fix options reset v1.3.6 - Fix suggested posts not being removed - Add option to collapse suggested posts and sponsored/pixeled articles instead of remove - Changed default for some settings v1.3.5 - Fix buttons in certain overlays not being clickable v1.3.4 - Option to remove inline suggestions - Fix buttons on menus in the settings not being clickable - Fix logging option not showing proper state on options page v1.3.3 - Fix Facebook page links no longer opening in an overlay. v1.3.2 - Fix mobile article links not being clickable BUG - Facebook page links that are meant to open in an overlay instead open in a new window/tab v1.3.1 - Make log messages optional v1.3.0 - Add support for mobile site - Add a link to the options page to the menu on mobile site - Option to remove pixeled articles like "Suggested Posts" - Options page improvements v1.2.0 - Add support for videos - Add options to enable/disable link and video tracking removal independently - Misc code cleanup v1.1.1 - Make backwards compatible with older FF - Make style applied to 'fixed' links configurable v1.1.0 (FF v48+ only) - Add options page with outline toggle v1.0.0: - Remove link tracking and add green dashed border to fixed links. ================================================ FILE: LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: README.md ================================================ [![GitHub release (latest by date)](https://img.shields.io/github/v/release/mgziminsky/FacebookTrackingRemoval?logo=github)](https://github.com/mgziminsky/FacebookTrackingRemoval/releases/latest) [![GitHub release (latest by date)](https://img.shields.io/github/downloads/mgziminsky/FacebookTrackingRemoval/latest/total)](https://github.com/mgziminsky/FacebookTrackingRemoval/releases/latest) [![GitHub release (total)](https://img.shields.io/github/downloads/mgziminsky/FacebookTrackingRemoval/total)](https://github.com/mgziminsky/FacebookTrackingRemoval/releases) [![Mozilla Add-on](https://img.shields.io/amo/v/facebook-tracking-removal.svg?logo=firefoxbrowser)](https://addons.mozilla.org/addon/facebook-tracking-removal?src=external-github) [![Mozilla Add-on](https://img.shields.io/amo/d/facebook-tracking-removal.svg)](https://addons.mozilla.org/addon/facebook-tracking-removal?src=external-github) [![Mozilla Add-on](https://img.shields.io/amo/users/facebook-tracking-removal.svg)](https://addons.mozilla.org/addon/facebook-tracking-removal?src=external-github) [![Mozilla Add-on](https://img.shields.io/amo/stars/facebook-tracking-removal.svg)](https://addons.mozilla.org/addon/facebook-tracking-removal/reviews?src=external-github) [![Chrome Web Store](https://img.shields.io/chrome-web-store/v/ldeofbdmhnnocclkaddcnamhbhanaiaj.svg?logo=googlechrome)](https://chrome.google.com/webstore/detail/facebook-tracking-ad-remo/ldeofbdmhnnocclkaddcnamhbhanaiaj) [![Chrome Web Store](https://img.shields.io/chrome-web-store/users/ldeofbdmhnnocclkaddcnamhbhanaiaj.svg)](https://chrome.google.com/webstore/detail/facebook-tracking-ad-remo/ldeofbdmhnnocclkaddcnamhbhanaiaj) [![Chrome Web Store](https://img.shields.io/chrome-web-store/rating-count/ldeofbdmhnnocclkaddcnamhbhanaiaj.svg)](https://chrome.google.com/webstore/detail/facebook-tracking-ad-remo/ldeofbdmhnnocclkaddcnamhbhanaiaj) [![Chrome Web Store](https://img.shields.io/chrome-web-store/stars/ldeofbdmhnnocclkaddcnamhbhanaiaj.svg)](https://chrome.google.com/webstore/detail/facebook-tracking-ad-remo/ldeofbdmhnnocclkaddcnamhbhanaiaj) # Facebook™ Tracking & Ad Removal Removes Ads and the user interaction tracking from content on Facebook™. Modified elements can optionally have a custom CSS style applied to them so that cleaned items can be more easily identified. For links, the event listeners on the link and its parents are removed and/or disabled and a proper href is set on the link. For videos on mobile, all Facebook™ event-listeners and custom controls are removed, and the video is simplified into just the bare HTML5 video tag. ## Explanation of permissions: ![GitHub manifest.json dynamic](https://img.shields.io/github/manifest-json/permissions/mgziminsky/FacebookTrackingRemoval?label=Permissions) - Access to `facebook.com`, `messenger.com`, and `facebookwkhpilnemxj7asaniu7vnjjbiltxjqhye3mhbshg7kx5tfyd.onion` is needed for main functionality, in order to work on those pages. - Access to `mgziminsky.gitlab.io`, more specifically `https://mgziminsky.gitlab.io/FacebookTrackingRemoval/*`, is used to download blocking rules only - `webNavigation`: Needed to handle cleaning FB interactions that use the browser history API instead of doing a normal page navigation - Firefox: "Access browser activity during navigation" - Chrome: "Read your browsing history" - This is misleading. See [here](https://github.com/mgziminsky/FacebookTrackingRemoval/issues/67#issuecomment-1346953059) ## Privacy Policy I don't, and never will, collect or send any data to myself or any third parties ================================================ FILE: _locales/en/messages.json ================================================ { "extensionName": { "message": "Tracking & Ad Removal on FaceBk", "description": "Name of the extension." }, "extensionDescription": { "message": "Removes Ads and the user interaction tracking from content on Facebook™", "description": "Description of the extension." }, "optsTitle": { "message": "Tracking & Ad Removal for Facebook™ Options", "description": "Options page title" }, "optsLegend": { "message": "Options" }, "optsReloadNotice": { "message": "Changes will be applied when this options page is closed", "description": "Options page notice about when changes will be applied" }, "optsEnabled": { "message": "Enabled" }, "optsFixLinks": { "message": "Remove tracking from external links" }, "optsInternal": { "message": "Remove tracking values from internal links (If something breaks, try disabling this first)" }, "optsInlineVids": { "message": "Inline videos on mobile (Only affects mobile; May increase data usage)" }, "optsPixeled": { "message": "Hide Sponsored articles" }, "optsSuggest": { "message": "Hide inline suggestions (eg: Suggested Posts, People You May Know)" }, "optsHideMethod": { "message": "Hide method:" }, "optsCollapse": { "message": "Collapse" }, "optsRemove": { "message": "Remove" }, "optsUseStyle": { "message": "Add styling to modified elements" }, "optsAdvanced": { "message": "Advanced Options" }, "optsStyleLabel": { "message": "Custom CSS style to be added to modified elements:" }, "optsStylePreview": { "message": "STYLE PREVIEW" }, "optsUserRules": { "message": "Custom CSS selectors to hide, one per-line. FOR TESTING PURPOSES ONLY" }, "optsUserRulesHover": { "message": "If you identify a new selector, please submit it in a PR" }, "optsUserRulesPlaceholder": { "message": "/* Syntax: css-selector[||innerText|/regex/,..] */\na>span:only-of-type,.someClass||Sponsored||/suggest(ed)?/\n.alwaysHideThis" }, "optsPending": { "message": "Enable pending/unconfirmed hiding rules" }, "optsPendingLink": { "message": "View list here" }, "optsLogging": { "message": "Display log messages in the console" }, "optsRefresh": { "message": "Refresh Rules" }, "optsRefreshHover": { "message": "Only once per $1 minutes", "description": "Rule refresh cooldown message" }, "optsDefaults": { "message": "Restore Defaults" }, "optsResetTitle": { "message": "Default" }, "optsResetAlt": { "message": "Reset" }, "optsCanvas": { "message": "Attempt detection of ads that use images for their label" }, "optsSensitivity": { "message": "Image detection sensitivity" }, "optsSenseHover": { "message": "Higher for stricter matching, lower for looser matching" } } ================================================ FILE: _locales/fr/messages.json ================================================ { "extensionName": { "message": "Suppression des publicités et de la surveillance sur FaceBk", "description": "Nom du module complémentaire." }, "extensionDescription": { "message": "Supprime les publicités et la surveillance des interactions des utilisateurs du site web Facebook™", "description": "Description du module complémentaire." }, "optsTitle": { "message": "Options du module complémentaire Suppression des publicités et de la surveillance pour Facebook™", "description": "Titre de la page des options" }, "optsLegend": { "message": "Options" }, "optsEnabled": { "message": "Activé" }, "optsFixLinks": { "message": "Supprimer la surveillance des liens vers l'extérieur du site" }, "optsInternal": { "message": "Supprimez les valeurs pour contrer la surveillance des liens internes au site (si quelque chose se casse, essayez de le désactiver d'abord)" }, "optsInlineVids": { "message": "Vidéos en ligne sur mobile (n'affecte que les mobiles; peut augmenter l'utilisation des données)" }, "optsPixeled": { "message": "Masquer les articles sponsorisés" }, "optsSuggest": { "message": "Masquer les suggestions en ligne (par exemple: messages suggérés, personnes que vous connaissez peut-être)" }, "optsHideMethod": { "message": "Méthode de dissimulation:" }, "optsCollapse": { "message": "Effondrement" }, "optsRemove": { "message": "Suppression" }, "optsUseStyle": { "message": "Ajouter la mise en page aux éléments modifiés" }, "optsAdvanced": { "message": "Options Avançées" }, "optsStyleLabel": { "message": "Feuille de Style CSS personnalisée à ajouter aux éléments modifiés:" }, "optsStylePreview": { "message": "Aperçu de la mise en page" }, "optsUserRules": { "message": "Sélection des feuilles de styles CSS personnalisées à masquer, une par ligne. À DES FINS DE TEST UNIQUEMENT" }, "optsUserRulesHover": { "message": "Si vous identifiez une nouvelle feuille de style CSS à sélectionner, veuillez la soumettre dans un message pour les programmeurs" }, "optsPending": { "message": "Activer les règles de dissimulation en attente ou non confirmées" }, "optsPendingLink": { "message": "Voir la liste ici" }, "optsLogging": { "message": "Afficher les messages de journalisation dans la console" }, "optsRefresh": { "message": "Actualiser les règles" }, "optsRefreshHover": { "message": "Une seule fois par $1 minute(s)", "description": "Message de compte à rebours de la règle de raffraichissemnt" }, "optsDefaults": { "message": "Restaurations des paramètres par défaut" }, "___": { "message": "From https://libretranslate.com/?source=en&target=fr" }, "optsResetTitle": { "message": "Par défaut" }, "optsResetAlt": { "message": "Réinitialiser" }, "optsReloadNotice": { "message": "Les changements seront appliqués lorsque cette page d'options est fermée", "description": "Remarque sur la page des options sur quand les changements seront appliqués" } } ================================================ FILE: biome.json ================================================ { "$schema": "https://biomejs.dev/schemas/1.8.1/schema.json", "formatter": { "enabled": true, "indentWidth": 4, "indentStyle": "space", "lineWidth": 120, "ignore": ["webextension-polyfill", "browser-polyfill.*", ".vscode"] }, "linter": { "enabled": true, "ignore": ["webextension-polyfill", "browser-polyfill.*"], "rules": { "recommended": true, "suspicious": { "noAssignInExpressions": "off" } } }, "javascript": { "formatter": { "arrowParentheses": "asNeeded" } }, "json": { "parser": { "allowComments": true, "allowTrailingCommas": true } }, "vcs": { "enabled": true, "clientKind": "git", "useIgnoreFile": true } } ================================================ FILE: data/click_whitelist/elements ================================================ /* All entries must be all UPPERCASE */ INPUT SELECT BUTTON TEXTAREA ================================================ FILE: data/click_whitelist/roles ================================================ /* All entries must be all UPPERCASE */ BUTTON CHECKBOX COMBOBOX LINK MENUITEM MENUITEMCHECKBOX MENUITEMRADIO OPTION RADIO SLIDER TAB TEXTBOX ================================================ FILE: data/click_whitelist/selectors ================================================ /* Desktop */ a[data-jsid='actionLink'] a[ajaxify] a.see_more_link form div.pam a[rel='theater'] #stories_tray [role=presentation][data-tooltip-content] /* Chat emoji categories */ form [contenteditable="true"] form [contenteditable="true"]+div:last-child /* Post comment input */ /* Messenger page */ a[aria-label='photo'] /* photos */ span._40fu /* message actions */ /* Mobile */ span[data-sigil='more'] /* Chat */ div._5r8h img._358 ================================================ FILE: data/declarativeNetRequest.json ================================================ [ { "id": 1, "action": { "type": "block" }, "condition": { "resourceTypes": ["beacon", "ping"], "urlFilter": "||facebook.com" } }, { "id": 2, "action": { "type": "block" }, "condition": { "resourceTypes": ["beacon", "ping"], "urlFilter": "||messenger.com" } }, { "id": 3, "action": { "type": "block" }, "condition": { "resourceTypes": ["beacon", "ping"], "urlFilter": "||facebookwkhpilnemxj7asaniu7vnjjbiltxjqhye3mhbshg7kx5tfyd.onion" } }, { "id": 4, "action": { "type": "block" }, "condition": { "urlFilter": "||pixel.facebook.com" } }, { "id": 5, "action": { "type": "block" }, "condition": { "urlFilter": "|*://*.facebook.com/ajax/bz*" } }, { "id": 6, "action": { "type": "block" }, "condition": { "urlFilter": "|*://*.messenger.com/ajax/bz*" } }, { "id": 7, "action": { "type": "block" }, "condition": { "urlFilter": "|*://*.facebookwkhpilnemxj7asaniu7vnjjbiltxjqhye3mhbshg7kx5tfyd.onion/ajax/bz*" } }, { "id": 8, "action": { "type": "block" }, "condition": { "urlFilter": "|*://*.facebook.com/ajax/bnzai*" } }, { "id": 9, "action": { "type": "block" }, "condition": { "urlFilter": "|*://*.messenger.com/ajax/bnzai*" } }, { "id": 10, "action": { "type": "block" }, "condition": { "urlFilter": "|*://*.facebookwkhpilnemxj7asaniu7vnjjbiltxjqhye3mhbshg7kx5tfyd.onion/ajax/bnzai*" } }, { "id": 11, "action": { "type": "block" }, "condition": { "urlFilter": "|*://*.facebook.com/xti.php?*" } }, { "id": 12, "action": { "type": "block" }, "condition": { "urlFilter": "|*://*.messenger.com/xti.php?*" } }, { "id": 13, "action": { "type": "block" }, "condition": { "urlFilter": "|*://*.facebookwkhpilnemxj7asaniu7vnjjbiltxjqhye3mhbshg7kx5tfyd.onion/xti.php?*" } } ] ================================================ FILE: data/hide_rules/article_wrapper ================================================ article div._55wo div.mbm div.pagelet div[data-pagelet='RightRail']>*>* /* Sidebar - old */ #ssrb_rhc_start+div>*>* /* Sidebar - new */ div[role='complementary'] div>span:only-child>div:only-child>div:only-child /* Sidebar - newer */ div[role='complementary'] div>span:only-of-type>div:only-child /* Sidebar - newerer */ div[role='complementary'] div:has(>:is(div,span):empty) /* Sidebar - newererer */ div[role=article] div[aria-posinset] /* Feed article */ div.tr9rh885 /* Suggestions at top of user page */ div._6x84 /* Watch Sponsored */ div.dzwucfd1 /* Page banner suggestions */ div.x1pha0wt /* Marketplace Sponsored Label */ div[style].xnpuxes:first-child /* Marketplace Sponsored */ span>div>div.xod5an3 /* Marketplace Sidebar */ div[data-type='vscroller']>div[data-type='container'] /* Mobile Feed */ ================================================ FILE: data/hide_rules/content ================================================ /* Syntax: css-selector[||innerText,..] */ a>span:only-of-type,._3nlk,div>a:first-child,div>a[onmousedown],a[role=link],div[role=button],h3>*||Sponsored||Sponsorisé||Patrocinado||Publicidad||Gesponsert||Sponsorizzato||Sponsorizzata ================================================ FILE: data/hide_rules/pending ================================================ /* Syntax: css-selector[||innerText|/regex/,...] */ ================================================ FILE: data/hide_rules/sponsored/patterns ================================================ ================================================ FILE: data/hide_rules/sponsored/selectors ================================================ ._3nlk [aria-label] [aria-labelledby] a[role=link] a>span:only-of-type div[role=button] div>a:first-child div>a[onmousedown] h3>* use /* replaced with svg, leave temporarily for backward compatibility */ svg ================================================ FILE: data/hide_rules/sponsored/texts ================================================ /* * List from https://greasyfork.org/en/scripts/404309-facebook-hide-ads-a-k-a-sponsored-posts/code * */ /* af */ Geborg /* am */ የተከፈለበት ማስታወቂያ /* ar */ إعلان مُموَّل /* as */ পৃষ্ঠপোষকতা কৰা /* ay */ Yatiyanaka /* az */ Sponsor dəstəkli /* be */ Рэклама /* bg */ Спонсорирано /* bn */ সৌজন্যে /* br */ Paeroniet /* bs */ Sponzorirano /* ca */ Patrocinat /* cb */ پاڵپشتیکراو /* co */ Spunsurizatu /* cs */ Sponzorováno /* cx */ Giisponsoran /* cy */ Noddwyd /* da */ Sponsoreret /* de */ Gesponsert /* el */ Χορηγούμενη /* en */ Chartered /* en */ Sponsored /* eo */ Reklamo /* es,gl,pt */ Patrocinado /* es */ Publicidad /* et */ Sponsitud /* eu */ Babestua /* fa */ دارای پشتیبانی مالی /* fi */ Sponsoroitu /* fo */ Stuðlað /* fr */ Commandité /* fr */ Sponsorisé /* fy */ Sponsore /* ga */ Urraithe /* gn */ Oñepatrosinapyre /* gx */ Χορηγούμενον /* hi,mr,ne */ प्रायोजित /* hu */ Hirdetés /* id */ Bersponsor /* it */ Sponsorizzata /* it */ Sponsorizzato /* ja */ 広告 /* jv */ Disponsori /* kk */ Демеушілік көрсеткен /* km */ បានឧបត្ថម្ភ /* lo */ ໄດ້ຮັບການສະໜັບສະໜູນ /* mk */ Спонзорирано /* ml */ സ്പോൺസർ ചെയ്തത് /* mn */ Ивээн тэтгэсэн /* ms */ Ditaja /* nl */ Gesponsord /* or */ ପ୍ରଯୋଜିତ /* pa */ ਸਰਪ੍ਰਸਤੀ ਪ੍ਰਾਪਤ /* pl */ Sponsorowane /* ps */ تمويل شوي /* ru,uk */ Реклама /* sa */ प्रायोजितः | /* si */ අනුග්‍රහය දක්වන ලද /* so */ La maalgeliyey /* sv */ Sponsrad /* te */ స్పాన్సర్ చేసినవి /* th */ ได้รับการสนับสนุน /* tl */ May Sponsor /* tr */ Sponsorlu /* tz */ ⵉⴷⵍ /* ur */ تعاون کردہ /* vi */ Được tài trợ /* zh-Hans */ 赞助内容 /* zh-Hant */ 贊助 ================================================ FILE: data/hide_rules/suggested/patterns ================================================ ================================================ FILE: data/hide_rules/suggested/selectors ================================================ [aria-label] [aria-labelledby] div.native-text>span /* Mobile */ div[role="button"] h3 span[dir] use ================================================ FILE: data/hide_rules/suggested/texts ================================================ A Video You May Like Events You May Like Follow Games You May Like Join Page Stories You May Like People You May Know Popular Across Facebook Public Figures to Follow Reels Reels and short videos Related Pages Shop now Suggested for You Suggested Groups Suggested Live Gaming Video Suggested Pages Suggested Post This shop has added new items. TV Watchlist /* Polish */ Dołącz /* Join */ /* Swedish */ Reels och korta videor /* Reels and short videos */ /* From https://greasyfork.org/en/scripts/431970-fb-clean-my-feeds/code */ /* People you may know */ /* ar */ أشخاص قد تعرفهم /* bg */ които може би познавате /* bg */ Хора /* cs */ Koho možná znáte /* de */ die du kennen könntest /* de */ Personen /* el */ Άτομα που ίσως γνωρίζετε /* es */ Personas que quizá conozcas /* fi */ Ihmiset /* fi */ jotka saatat tuntea /* fr */ Connaissez-vous... /* he */ אנשים שאולי אתה מכיר /* id */ Orang yang Mungkin Anda Kenal /* it */ Persone che potresti conoscere /* ja */ あなたが知っているかもしれない人々 /* lv */ Cilvēki /* lv */ kurus tu varētu pazīt /* nl */ Mensen die je misschien kent /* pl */ które możesz znać /* pl */ Osoby /* pt */ Pessoas que talvez conheças /* ru */ которых вы можете знать /* ru */ Люди /* tr */ Tanıyor olabileceğin kişiler /* uk */ Люди /* uk */ яких Ви можете знати /* vi */ Những người bạn có thể biết /* zh-Hans */ 你可能认识的人 /* zh-Hant */ 你可能認識的人 /* Reels and short videos */ /* ar */ ريلز ومقاطع الفيديو القصيرة /* bg */ Ленти и кратки видеоклипове /* cs */ Sekvence a krátká videa /* de */ Reels und Kurzvideos /* el */ Reel και σύντομα βίντεο /* es */ Reels y vídeos cortos /* fi */ Keloja ja lyhyitä videoita /* fr */ Reels et vidéos courtes /* he */ סרטוני Reels וקטעי וידאו קצרים /* id */ Reels dan Video Pendek /* it */ Reel e video brevi /* ja */ リールとショート動画 /* lv */ Reels un īsi videoklipi /* nl */ Reels en korte video\s /* pl */ Rolki i krótkie filmy /* pt */ Vídeos do Reels e vídeos de curta duração /* ru */ Reels и короткие видео /* tr */ Makaralar ve kısa videolar /* uk */ Відео Reels і короткі відео /* vi */ Reels và video ngắn /* zh-Hans */ 卷轴和短视频 /* zh-Hant */ Reels 和短影片 /* Events you may like */ /* ar */ أحداث قد تعجبك /* bg */ които може да ви харесат /* bg */ Събития /* cs */ které se vám mohou líbit /* cs */ Události /* de */ die Ihnen gefallen könnten /* de */ Veranstaltungen /* el */ Εκδηλώσεις που μπορεί να σας αρέσουν /* es */ Eventos que te pueden gustar /* fi */ Kela/lyhyt video /* fr */ Évènements qui pourraient vous intéresser /* he */ אירועים שאולי תאהבו /* id */ Acara yang mungkin Anda sukai /* it */ Eventi che potrebbero piacerti /* ja */ リール/ショートビデオ /* lv */ kas jums varētu patikt /* lv */ Notikumi /* nl */ Evenementen die je misschien leuk vindt /* pl */ które mogą Ci się spodobać /* pl */ Wydarzenia /* pt */ Eventos que você pode gostar /* ru */ которые вам могут понравиться /* ru */ Мероприятия /* tr */ makara/kısa video /* uk */ Події /* uk */ які можуть вам сподобатися /* vi */ Sự kiện bạn có thể thích /* zh-Hans */ 您可能喜欢的活动 /* zh-Hant */ 你可能感興趣的活動 /* Follow */ /* ar */ تابع /* bg */ Следвай /* cs */ Sledovat /* de */ Folgen /* el */ Ακολούθησε /* es */ Seguir /* fi */ Seuraa /* fr */ Suivre /* he */ עקוב /* id */ Ikuti /* it */ Segui /* ja */ フォロー /* lv */ Sekot /* nl */ Volgen /* pl */ Obserwuj /* pt */ Seguir /* ru */ Подписаться /* tr */ Takip Et /* uk */ Слідуйте /* vi */ Theo dõi /* zh-Hans */ 关注 /* zh-Hant */ 追蹤 ================================================ FILE: data/hide_rules/suggestions_smart ================================================ /* Syntax: css-selector[||innerText,..] */ span[dir]||People You May Know||Suggested Post||Suggested for You||Suggested Groups||Public Figures to Follow||Suggested Pages||Suggested Live Gaming Video||Reels||Reels and short videos ================================================ FILE: data/hide_rules/unconditional ================================================ /* Selectors that will always be removed unconditionally and never collapsed */ .x12fkvr4 /* Marketplace sponsored hamburger menu */ a[href*="hoisted"] > span:not(:empty):only-child /* feed group suggestions */ ================================================ FILE: data/param_cleaning/params ================================================ _ft_ _nc_cat _rdr _sref_ acontext /* May break some links? Removed by Legitimate URL Shortener so try adding it again */ comment_tracking cref dti eav eid /* appears on everything... */ entry_point entrypoint epa /* appears on hashtags */ fb_ref fref from lst Medium paipv placement privacy_mutation_token rc ref referrer refid settings_tracking sfnsn tbua tracking ================================================ FILE: data/param_cleaning/prefix_patterns ================================================ __ ((\w*_)?source|hc)(\b|_) ft\[ pn_ ref_ referral zero_ ================================================ FILE: data/param_cleaning/values ================================================ extragetparams ================================================ FILE: jsconfig.json ================================================ { "compilerOptions": { "target": "esnext", "module": "esnext", "baseUrl": "./", "paths": { "/*": ["./*"] } }, "include": ["src/**/*"], "typeAcquisition": { "include": ["firefox-webext-browser"] } } ================================================ FILE: manifest.json ================================================ { "name": "__MSG_extensionName__", "version": "1.13.0", "description": "__MSG_extensionDescription__", "default_locale": "en", "icons": { "128": "src/icon.png" }, "author": "Michael Ziminsky", "homepage_url": "https://github.com/mgziminsky/FacebookTrackingRemoval", "browser_specific_settings": { "gecko": { "id": "{bb1b80be-e6b3-40a1-9b6e-9d4073343f0b}", "strict_min_version": "113.0" } }, "permissions": ["alarms", "declarativeNetRequestWithHostAccess", "scripting", "storage", "webNavigation"], "host_permissions": [ "*://*.facebook.com/*", "*://*.messenger.com/*", "*://*.facebookwkhpilnemxj7asaniu7vnjjbiltxjqhye3mhbshg7kx5tfyd.onion/*", "https://mgziminsky.gitlab.io/FacebookTrackingRemoval/*" ], "options_ui": { "page": "src/options/options.html", "open_in_tab": false }, "background": { "type": "module", "scripts": ["src/background/background.js"], "service_worker": "src/background/background.js" }, "action": { "default_icon": "src/icon.png", "default_popup": "src/options/options.html" }, "page_action": { "default_icon": "src/icon.png", "default_popup": "src/options/options.html", "show_matches": [ "*://*.facebook.com/*", "*://*.messenger.com/*", "*://*.facebookwkhpilnemxj7asaniu7vnjjbiltxjqhye3mhbshg7kx5tfyd.onion/*" ] }, "content_scripts": [ { "all_frames": true, "matches": [ "*://*.facebook.com/*", "*://*.messenger.com/*", "*://*.facebookwkhpilnemxj7asaniu7vnjjbiltxjqhye3mhbshg7kx5tfyd.onion/*" ], "css": ["src/content_script/app.css"], "js": ["browser-polyfill.min.js", "src/content_script/content_script.js"], "run_at": "document_end", "world": "ISOLATED" } ], "web_accessible_resources": [ { "use_dynamic_url": true, "matches": [ "*://*.facebook.com/*", "*://*.messenger.com/*", "*://*.facebookwkhpilnemxj7asaniu7vnjjbiltxjqhye3mhbshg7kx5tfyd.onion/*" ], "resources": ["/src/*"] } ], "declarative_net_request": { "rule_resources": [ { "id": "ruleset", "enabled": true, "path": "data/declarativeNetRequest.json" } ] }, "incognito": "spanning", "manifest_version": 3 } ================================================ FILE: package.sh ================================================ #!/bin/bash set -x cd $(dirname $0) rm -f Browser_Extension.zip cp webextension-polyfill/dist/browser-polyfill.min.js* ./ zip -r -ll Browser_Extension.zip . -i 'src/*' '_locales/*' 'data/*' browser-polyfill.min.js manifest.json CHANGELOG LICENSE ================================================ FILE: src/background/background.js ================================================ /* This file is part of FacebookTrackingRemoval. FacebookTrackingRemoval is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. FacebookTrackingRemoval is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with FacebookTrackingRemoval. If not, see . Copyright (C) 2016-2024 Michael Ziminsky */ import "/browser-polyfill.min.js"; import { isChrome, log, warn } from "../common.js"; import { options, storage } from "../config.js"; import { CHROME_PORT, MSG, NOOP, STYLE_CLASS } from "../consts.js"; import { refreshRules } from "../rules_sync.js"; import "./webrequest.js"; browser.action.disable(); // Default to disabled. Content script will send message to enable // Do some cleanup after updating to 1.6.4+ for the first time // to get rid of old storage data that is no longer used browser.runtime.onInstalled.addListener(details => { // Not an update if (!details.previousVersion || details.previousVersion === browser.runtime.getManifest().version) return; // Always force refresh rules after an update for simplicity // 1.8.0 changed the dynamic rules format browser.storage.local.remove(["lastRuleRefresh", "hide_rules"]).finally(refreshRules.bind(undefined, true)); const old = [1, 6, 3]; const prev = details.previousVersion.split(".").map(Number); if (!details.temporary && prev.every((v, i) => v <= (old[i] ?? 0))) { const currentOpts = options; storage.clear(); browser.storage.local.clear(); storage.set(currentOpts); browser.runtime.reload(); } }); /** * @param {(injection: browser.scripting.CSSInjection) => Promise} action * @param {string?} style * @param {number} tabId * @param {number} frameId */ function updateCSS(action, style, tabId, frameId) { action({ target: { tabId, frameIds: [frameId], }, origin: "USER", css: style ? `.${STYLE_CLASS} { ${style}; }` : "", }).catch(warn); } /** * @param {{msg: string}} * @param {browser.runtime.MessageSender} sender */ function onMessage({ msg, ...data }, sender) { switch (msg) { case MSG.actionEnable: browser.action.enable(sender.tab.id); break; case MSG.insertCss: updateCSS(browser.scripting.insertCSS, data.style, sender.tab.id, sender.frameId); break; case MSG.removeCss: updateCSS(browser.scripting.removeCSS, data.style, sender.tab.id, sender.frameId); break; case MSG.rulesRefresh: return refreshRules(data.force); } } browser.runtime.onMessage.addListener(onMessage); if (isChrome) { // alarms have a min delay of 1 minute... refreshRules().catch(NOOP); // Popups don't fire unload on close, have to handle it from here browser.runtime.onConnect.addListener(port => { log("Options Connect"); if (port.name === CHROME_PORT) { let changes = {}; port.onMessage.addListener(data => (changes = data)); port.onDisconnect.addListener(() => { log("Options Disconnect"); if (Object.keys(changes).length) Object.assign(options, changes); }); } }); } ================================================ FILE: src/background/webrequest.js ================================================ /** * Copyright (C) 2023-2024 Michael Ziminsky (Z) * * This file is part of FacebookTrackingRemoval. * * FacebookTrackingRemoval is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * FacebookTrackingRemoval is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with FacebookTrackingRemoval. If not, see . */ import * as config from "../config.js"; import { MSG } from "../consts.js"; import { cleanLinkParams } from "../util.js"; browser.webNavigation.onHistoryStateUpdated.addListener( details => { if (!config.options.enabled) return; const orig = details.url; const clean = cleanLinkParams(details.url); if (orig !== clean) { browser.tabs.sendMessage(details.tabId, { type: MSG.history, orig, clean }); } }, { url: config.host_patterns.map(h => h.replaceAll(/[^.\w]/g, "")).map(hostContains => ({ hostContains })), }, ); function updateRuleset(enable) { if (enable === true) { browser.declarativeNetRequest.updateEnabledRulesets({ enableRulesetIds: ["ruleset"] }); } else if (enable === false) { browser.declarativeNetRequest.updateEnabledRulesets({ disableRulesetIds: ["ruleset"] }); } } config.storage.onChanged.addListener(({ enabled }) => updateRuleset(enabled?.newValue)); browser.runtime.onInstalled.addListener(() => { // Disable blocking rules on update since they get reset back to the extension default config.READY.then(() => updateRuleset(config.options.enabled)); }); ================================================ FILE: src/common.js ================================================ /* This file is part of FacebookTrackingRemoval. FacebookTrackingRemoval is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. FacebookTrackingRemoval is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with FacebookTrackingRemoval. If not, see . Copyright (C) 2016-2024 Michael Ziminsky */ import { options } from "./config.js"; export { isChrome, log, warn }; const isChrome = Object.getPrototypeOf(browser) !== Object.prototype; function log(arg) { if (options.logging) log_to(console.log, arg); } function warn(arg) { if (options.logging) log_to(console.warn, arg); } function log_to(logger, arg) { if (typeof arg === "function") { const res = arg(); if (res) logger(res); } else { logger(arg); } } ================================================ FILE: src/config.js ================================================ /** * Copyright (C) 2023-2024 Michael Ziminsky (Z) * * This file is part of FacebookTrackingRemoval. * * FacebookTrackingRemoval is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * FacebookTrackingRemoval is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with FacebookTrackingRemoval. If not, see . */ import { joinSelectors, normalizeString } from "./util.js"; export { click_whitelist, defaults, domains, hide_rules, host_patterns, initHideRule, MAX_CANVAS_SENSITIVITY, onChanged, options, param_cleaning, READY, reset, storage, }; const storage = browser.storage.local; const MAX_CANVAS_SENSITIVITY = 2; /** @type {Options} */ const defaults = Object.freeze({ enabled: true, fixLinks: true, internalRefs: false, inlineVids: false, fixVideos: false, delPixeled: true, delSuggest: true, hideMethod: "collapse", useStyle: false, logging: false, modStyle: "outline: 1px dashed rgba(0, 128, 0, 0.5) !important;", userRules: "", pendingRules: false, testCanvas: true, canvasSensitivity: 0.8, }); const host_patterns = Object.freeze([ ...new Set(browser.runtime.getManifest().content_scripts.flatMap(cs => cs.matches)), ]); const domains = Object.freeze([...new Set(host_patterns.map(m => m.replace(/\W*\*\W?/g, "")))]); /** @type {Options} */ const _options = Object.seal(Object.assign({}, defaults)); const options = new Proxy(_options, { set(opts, prop, val) { if (!Object.hasOwn(opts, prop)) return false; const old = opts[prop]; opts[prop] = val ?? defaults[prop]; let apply; if (val != null) { apply = storage.set.bind(storage, { [prop]: val }); } else { apply = storage.remove.bind(storage, prop); } apply().catch(() => (opts[prop] = old)); return true; }, deleteProperty(opts, prop) { const old = opts[prop]; opts[prop] = defaults[prop]; storage.remove(prop).catch(() => (opts[prop] = old)); return false; }, }); /** * Reset option value(s) to the default * * @param {?string | string[]} keys * @return {Promise} */ function reset(keys) { let result; if (keys) { result = storage.remove(keys).then(() => { for (const key of [...keys]) _options[key] = defaults[key]; }); } else { result = storage.remove(Object.keys(defaults)).then(() => Object.assign(_options, defaults)); } return result; } const _data = Object.freeze({ hide_rules: Object.freeze({ /**@type {HideRules}*/ value: { article_wrapper: "", pending: {}, sponsored: {}, suggested: {}, unconditional: "" }, update(/**@type {HideRules}*/ raw) { Object.assign(this.value, raw); Object.values(this.value).forEach(initHideRule); }, }), param_cleaning: Object.freeze({ /**@type {ParamCleaning}*/ value: { params: [], prefix_patterns: ["$"], values: [] }, update(/**@type {ParamCleaning}*/ raw) { Object.assign(this.value, raw); this.value.pattern = new RegExp(`^(${this.value.prefix_patterns.join("|")})`); }, }), click_whitelist: Object.freeze({ /**@type {ClickWhitelist}*/ value: { elements: [], roles: [], selectors: [] }, update(/**@type {ClickWhitelist}*/ raw) { Object.assign(this.value, raw); this.value.selector = joinSelectors(this.value.selectors.join("\n")); }, }), }); /** @type {ProxyHandler} */ const ReadOnly = { set: () => false, isExtensible: () => false, defineProperty: () => { throw new Error("Not Allowed"); }, deleteProperty: () => { throw new Error("Not Allowed"); }, }; /** @type {[HideRules, ParamCleaning, ClickWhitelist]} */ const [hide_rules, param_cleaning, click_whitelist] = [ new Proxy(_data.hide_rules.value, ReadOnly), new Proxy(_data.param_cleaning.value, ReadOnly), new Proxy(_data.click_whitelist.value, ReadOnly), ]; /** * Converts the texts and patterns of a rule to final format * @param {Object} rule * @param {string[]?} rule.texts * @param {string[]?} rule.patterns * * @returns {HideRule} */ function initHideRule(rule) { if (rule.texts) rule.texts = rule.texts.reduce((m, t) => m.set(normalizeString(t), t), new Map()); if (Array.isArray(rule.patterns) && rule.patterns.length) rule.patterns = new RegExp(rule.patterns.join("|"), "iu"); // biome-ignore lint/performance/noDelete: else delete rule.patterns; return rule; } const _onChanged = new Set(); /** @type {WebExtEvent<(changes: { [key: string]: browser.storage.StorageChange }) => void>} */ const onChanged = Object.freeze({ addListener(cb) { if (typeof cb === "function") _onChanged.add(cb); }, removeListener: _onChanged.delete.bind(_onChanged), hasListener: _onChanged.has.bind(_onChanged), }); /** * Update local options with value from storage * * @param {string | string[]} keys */ async function sync(keys) { const { opts, rules } = [...keys].reduce( (acc, key) => { if (key in defaults) acc.opts[key] = defaults[key]; else if (key in _data) acc.rules[key] = _data[key].value; return acc; }, { opts: {}, rules: {} }, ); const result = []; if (Object.keys(opts).length) result.push(storage.get(opts).then(opts => Object.assign(_options, opts))); if (Object.keys(rules).length) result.push( storage.get(rules).then(rules => { for (const k in rules) _data[k].update(rules[k]); }), ); return Promise.allSettled(result); } storage.onChanged.addListener(changes => { sync(Object.keys(changes)).then(() => { for (const k of Object.keys(_data)) delete changes[k]; if (Object.keys(changes).length) for (const cb of _onChanged.values()) cb(changes); }); }); const READY = new Promise((res, rej) => { Promise.all([ storage.get(defaults).then(vals => Object.assign(_options, vals)), browser.storage.local.get(Object.keys(_data)).then(data => { for (const k in data) _data[k].update(data[k]); }), ]).then(() => res(), rej); }); ================================================ FILE: src/consts.js ================================================ export const RATE_LIMIT = 1000 * 60 * 15; // 15 min export const STYLE_CLASS = "fbtrStyled"; export const PROCESSED_CLASS = "FBTR-PROCESSED"; export const COLLAPSED_SELECTOR = ".fbtrHidden"; export const NOOP = () => {}; export const MSG = Object.freeze({ actionEnable: "ACTION_ENABLE", history: "HISTORY", insertCss: "INSERT_CSS", removeCss: "REMOVE_CSS", rulesRefresh: "RULES", }); export const CHROME_PORT = "CHROME_POPUP"; ================================================ FILE: src/content_script/app.css ================================================ /* This file is part of FacebookTrackingRemoval. FacebookTrackingRemoval is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. FacebookTrackingRemoval is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with FacebookTrackingRemoval. If not, see . Copyright (C) 2016-2024 Michael Ziminsky */ /* Make mobile article links clickable */ section.touchable > a { position: absolute; width: 100%; height: 100%; top: 0; left: 0; z-index: 41; } details.fbtrHidden { padding: 0 10px; } details.fbtrHidden[open] { padding-bottom: 10px; } summary.fbtrLabel { padding: 0.5rem 0; cursor: pointer; font-size: 0.8rem; color: var(--secondary-text); } .fbtrHide { display: none; } /* Emergency Broadcast posts. eg: Amber Alert */ ._3j6k { border: medium solid red !important; } ================================================ FILE: src/content_script/app.js ================================================ /* This file is part of FacebookTrackingRemoval. FacebookTrackingRemoval is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. FacebookTrackingRemoval is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with FacebookTrackingRemoval. If not, see . Copyright (C) 2016-2024 Michael Ziminsky */ import { log } from "../common.js"; import { READY, hide_rules, initHideRule, onChanged, options } from "../config.js"; import { COLLAPSED_SELECTOR, MSG, PROCESSED_CLASS } from "../consts.js"; import { normalizeString, parseHideRules } from "../util.js"; import { computeCanvasPrints, testCanvas } from "./canvas_fingerprint.js"; import { applyStyle, cleanRedirectLinks, cleanShimLinks, fixGifs, fixVideoLinks, stripFBCLID, stripRefs, } from "./cleaning.js"; import { applyEventBlockers, ariaText, buildCollapsible, inlineUse, selectAllWithBase, visibleText } from "./dom.js"; browser.runtime.sendMessage({ msg: MSG.actionEnable }); /** @param {Element} target */ function isCollapsed(target) { return !!target.closest(COLLAPSED_SELECTOR); } /** * @param {Element} elem * @param {string} label * @param {"remove" | "collapse"} method */ function hide(elem, label, method) { /** @type {Element} */ let target; if (!(elem && (target = elem.closest(hide_rules.article_wrapper)))) { log(`Unable to hide ${label} - ${elem}`); return; } log(() => { const selector = hide_rules.article_wrapper; for (const s of selector.split(",")) { if (target.matches(s)) { return `>>> Wrapper matched for ${target.tagName}: ${selector} = ${s}`; } } }); if (method === "collapse") { if (isCollapsed(target)) { log(`${label} already collapsed`); return; } const wrapper = buildCollapsible(label); applyStyle(wrapper); for (const c of target.classList) wrapper.classList.add(c); target.classList.add(PROCESSED_CLASS); target.parentNode.appendChild(wrapper); wrapper.appendChild(target); log(`Collapsed ${label}`); } else { // Removing breaks things :/ Consider using class instead of inline style? (target.closest(":not(:only-child)") || target).style = "display: none !important"; log(`Removed ${label}`); } } function removeLinkTracking(node) { const cleaned = cleanShimLinks(node) + fixVideoLinks(node) + cleanRedirectLinks(node) + stripFBCLID(node); fixGifs(node); if (cleaned) applyEventBlockers(node); return cleaned; } /** * @param {Element} node * @param {HideRule} rule * @param {"remove" | "collapse"} [method=options.hideMethod] */ function removeArticles(node, { selector, texts, patterns }, method = options.hideMethod) { if (!selector || node.classList.contains(PROCESSED_CLASS)) return; /** @argument {string} text */ const getMatch = text => { if (!(texts?.size || patterns)) return text || "Unconditional Hide"; // Some sponsored have other details appended after a · (0xb7). Try matching both parts separately const parts = text.split("\xb7").map(s => s.trim().toLowerCase()); if (patterns && parts.some(p => patterns.test(p))) return text; for (const p of parts) { const x = texts.get(normalizeString(p)); if (x) return x; } }; for (const e of selectAllWithBase(node, selector)) { const elementText = ariaText(e) || visibleText(e); const match = getMatch(elementText); if (match) { log(() => { for (const s of selector.split(",")) { if (e.matches(s)) { return `>>> Rule matched for ${elementText}: ${selector} = ${s}`; } } }); hide(e, match, method); } } } let fprintsComputed = false; /** @param {HTMLCanvasElement} canvas */ function removeCanvasArticle(canvas) { if (isCollapsed(canvas) || canvas.classList.contains(PROCESSED_CLASS)) return; if (!fprintsComputed) { const texts = new Set(userRules.texts.values()); if (options.delPixeled) { for (const text of hide_rules.sponsored.texts.values()) texts.add(text); } if (options.delSuggest) { for (const text of hide_rules.suggested.texts.values()) texts.add(text); } if (options.pendingRules) { for (const text of hide_rules.pending.texts.values()) texts.add(text); } computeCanvasPrints(texts, canvas); fprintsComputed = true; } try { const ctx = canvas.getContext("2d"); const tform = ctx.getTransform(); ctx.resetTransform(); const match = testCanvas(ctx); ctx.setTransform(tform); if (match) { log(() => `>>> Canvas matched for "${match}"`); hide(canvas, match, options.hideMethod); } } catch (error) { watchCanvas(canvas); } } function removeAll(target) { removeArticles(target, userRules); if (options.delSuggest) removeArticles(target, hide_rules.suggested); if (options.delPixeled) { removeArticles( target, hide_rules.sponsored, document.location.pathname.startsWith("/marketplace") ? "remove" : options.hideMethod, ); removeArticles(target, { selector: hide_rules.unconditional }, "remove"); } if (options.pendingRules) removeArticles(target, hide_rules.pending); if (options.testCanvas) for (const canvas of selectAllWithBase(target, "canvas")) { removeCanvasArticle(canvas); } if (options.internalRefs) stripRefs(target); } /** * @param {MutationRecord} mutation * @param {(n: Node) => void} cb */ function forEachAdded(mutation, cb) { for (const node of mutation.addedNodes) { if ( node.nodeType === Node.ELEMENT_NODE && !SKIP.includes(node.nodeName) && !node.classList.contains(PROCESSED_CLASS) ) { cb(node); } } } /** @type {Map} */ const pendingRefs = new Map(); /** * Find any new elements that reference nodes that don't yet exist * @param {Element} target */ function findPending(target) { for (const elem of selectAllWithBase(target, "[aria-labelledby]")) { if (elem.closest(COLLAPSED_SELECTOR)) continue; for (const attr of elem.getAttribute("aria-labelledby")?.split(" ") ?? []) { if (!document.getElementById(attr)) { log(() => `New pending element referencing [${attr}]`); if (!pendingRefs.has(attr)) pendingRefs.set(attr, []); pendingRefs.get(attr).push(elem); } } } } /** Check if any of the ids we are waiting for were added, and if so process their nodes */ function processPending() { for (const [id, elems] of pendingRefs.entries()) { if (document.getElementById(id)) { log(() => `Waited on element now present for [${id}]`); pendingRefs.delete(id); for (const elem of elems) { removeAll(elem); } } } } const SKIP = ["SCRIPT", "STYLE", "LINK"]; const observer = new MutationObserver(mutations => { processPending(); for (const mutation of mutations) { if (mutation.type === "childList" && !SKIP.includes(mutation.target.nodeName)) { const target = mutation.target; inlineUse(target); removeAll(target); if (!options.testCanvas) forEachAdded(mutation, findPending); if (options.fixLinks) forEachAdded(mutation, removeLinkTracking); forEachAdded(mutation, node => node.classList.add(PROCESSED_CLASS)); } else if (mutation.target) { if (options.fixLinks) removeLinkTracking(mutation.target); if (options.internalRefs) stripRefs(mutation.target); } } }); function watchCanvas(canvas) { new MutationObserver(([record, ...rest], obs) => { obs.takeRecords(); obs.disconnect(); setTimeout(() => removeCanvasArticle(record.target), 100); }).observe(canvas, { attributeFilter: ["width", "height"], }); } /** @type {HideRule} */ let userRules; async function run() { userRules = initHideRule(parseHideRules(options.userRules)); const body = document.body; observer.disconnect(); removeAll(body); observer.observe( body, (() => { const opts = { childList: true, subtree: true, characterData: false }; if (options.fixLinks) { opts.attributes = true; opts.attributeFilter = ["href"]; } return opts; })(), ); if (options.fixLinks && removeLinkTracking(body) && document.getElementById("newsFeedHeading")) { const feed = document.getElementById("newsFeedHeading").parentNode; for (const stream of feed.querySelectorAll("div._4ikz")) { applyEventBlockers(stream); } } } /** @param {{type: string}} */ function handleMessage({ type, ...data }) { switch (type) { case MSG.history: if (!history.state.fbtr_clean) { history.replaceState(Object.assign({ fbtr_clean: true }, history.state), "", data.clean); log(`Cleaned link navigation done via history.pushState:\n\t${data.orig}\n\t${data.clean}`); } break; } } let activeStyle; function start() { run(); browser.runtime.onMessage.addListener(handleMessage); if (activeStyle) browser.runtime.sendMessage({ msg: MSG.removeCss, style: activeStyle }); if (options.useStyle) browser.runtime.sendMessage({ msg: MSG.insertCss, style: (activeStyle = options.modStyle) }); } function stop() { observer.disconnect(); browser.runtime.onMessage.removeListener(handleMessage); browser.runtime.sendMessage({ msg: MSG.removeCss, style: activeStyle }); } onChanged.addListener(() => (options.enabled ? start() : stop())); READY.then(() => { if (options.enabled) start(); }); ================================================ FILE: src/content_script/canvas_fingerprint.js ================================================ /** * Copyright (C) 2024 Michael Ziminsky (Z) * * This file is part of FacebookTrackingRemoval. * * FacebookTrackingRemoval is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * FacebookTrackingRemoval is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with FacebookTrackingRemoval. If not, see . */ import { log } from "../common.js"; import { MAX_CANVAS_SENSITIVITY, hide_rules, options } from "../config.js"; export { computeCanvasPrints, testCanvas }; /** @type {Map} */ const canvasPrints = new Map(); /** * Measures the "empty" spaces between the first and last "opaque" pixels of a 1D, 1-pixel high row of a rendered canvas * @param {Uint8ClampedArray} data An array of pixels for a singal row from a canvas rendering context * as retured by `ctx.getImageData(x, y, ctx.canvas.width, 1)` */ function gaps(data) { const ALPHA = 180; // somewhat arbitrary based on some manual checks const start = data.findIndex((n, i) => n >= ALPHA && !((i + 1) % 4)); if (start < 0) throw "Empty data"; const end = data.findLastIndex((n, i) => n >= ALPHA && !((i + 1) % 4)); const fprint = []; for (let i = start, gap = 0, empty = false; i <= end; i += 4) { const val = data[i]; if (empty !== val < ALPHA) { if (empty) fprint.push(gap); empty = !empty; gap = 0; } ++gap; } return fprint; } /** * @param {CanvasRenderingContext2D} ctx * @param {string} [txt] */ function fingerprintCanvas(ctx, txt) { const mid = ctx.canvas.height / 2; const off = ctx.measureText("").alphabeticBaseline / 2; if (txt) { ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); ctx.fillText(txt, 0, mid); } const slice = ctx.getImageData(0, mid - off, ctx.canvas.width, 1).data; return gaps(slice); } /** * @param {Iterable} texts * @param {Element} [ref=document.body] */ async function computeCanvasPrints(texts, ref) { canvasPrints.clear(); const ctx = new OffscreenCanvas(300, 50).getContext("2d", { willReadFrequently: true }); const style = getComputedStyle(ref ?? document.body); ctx.font = style.font; ctx.fillStyle = style.color; ctx.textBaseline = "middle"; for (const text of texts) { const fprint = fingerprintCanvas(ctx, text); if (fprint) canvasPrints.set(text, fprint); } } /** * Check if the canvas context matches one of the recognized fingerprints * as calculated by {@link computeCanvasPrints} * @param {CanvasRenderingContext2D} ctx */ function testCanvas(ctx) { const fprint = fingerprintCanvas(ctx); if (!fprint) return; /** @type {[number, string][]} */ let matches = []; for (const [txt, print] of canvasPrints.entries()) { if (fprint.length !== print.length) continue; let sumSq = 0; for (let i = 0; i < print.length; i++) { const diff = Math.abs(fprint[i] - print[i]); sumSq += diff * diff; } const stdDev = Math.sqrt(sumSq / fprint.length); if (stdDev < Number.EPSILON) { matches = [[0, txt]]; break; } if (stdDev < MAX_CANVAS_SENSITIVITY - options.canvasSensitivity) { matches.push([stdDev, txt]); } } if (matches.length) { const [stdDev, txt] = matches.reduce((min, match) => (match < min ? match : min)); log(() => `Canvas matched fingerprint for "${txt}": ${stdDev}`); return txt; } } ================================================ FILE: src/content_script/cleaning.js ================================================ /** * Copyright (C) 2023-2024 Michael Ziminsky (Z) * * This file is part of FacebookTrackingRemoval. * * FacebookTrackingRemoval is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * FacebookTrackingRemoval is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with FacebookTrackingRemoval. If not, see . */ import { log } from "../common.js"; import { domains, options } from "../config.js"; import { STYLE_CLASS } from "../consts.js"; import { cleanLinkParams } from "../util.js"; import { applyEventBlockers, cleanAttrs, selectAllWithBase, stopPropagation } from "./dom.js"; export { applyStyle, cleanShimLinks, cleanRedirectLinks, fixGifs, fixVideoLinks, stripFBCLID, stripRefs }; function applyStyle(elem) { elem.classList.add(STYLE_CLASS); } const supportedProtos = ["http:", "https:", "ftp:"]; function cleanLink(a, href) { cleanAttrs(a); a.target = "_blank"; a.rel = "noreferrer noopener"; try { if (supportedProtos.includes(new URL(href, origin).protocol)) a.href = href; else log(`Unsupported link protocol; leaving unchanged: ${href}`); } catch (_) { log(`Link cleaning encountered an invalid url: ${href}`); } applyStyle(a); } function buildVideo(src, poster) { const video = document.createElement("video"); video.preload = "metadata"; video.controls = true; video.poster = poster; video.setAttribute("width", "100%"); video.src = src; applyStyle(video); return video; } // Desktop only function cleanShimLinks(node) { const trackedLinks = selectAllWithBase(node, "a[onclick^='LinkshimAsyncLink.referrer_log']"); for (const a of trackedLinks) { cleanLink(a, extractQuotedString(a.getAttribute("onmouseover")).replace(/\\(.)/g, "$1")); log(`Removed tracking from shim link: ${a}`); } return trackedLinks.length; } // Mobile only function fixVideoLinks(node) { const videoLinks = selectAllWithBase(node, "div[data-sigil=inlineVideo],a[href^='/video_redirect/']"); for (const vid of videoLinks) { const vidSrc = vid.tagName === "DIV" ? JSON.parse(vid.getAttribute("data-store")).src // Phone : new URL(vid.href).searchParams.get("src"); // m.facebook const replaceVideo = target => { const img = target.querySelector(".img,img"); // phone,m.facebook const poster = extractQuotedString(img.style.backgroundImage) || img.src; const video = buildVideo(vidSrc, poster); target.parentNode.replaceChild(video, target); return video; }; if (options.inlineVids) { log(`Inlined video: ${replaceVideo(vid).src}`); } else { cleanAttrs(vid); const target = vid.cloneNode(true); applyStyle(target); target.classList.add("FBTR-SAFE"); target.addEventListener( "click", e => { e.stopImmediatePropagation(); e.stopPropagation(); replaceVideo(target).play(); }, true, ); vid.parentNode.replaceChild(target, vid); log(`Cleaned deferred inline video: ${vidSrc}`); } } return videoLinks.length; } // Desktop and Mobile function cleanRedirectLinks(node) { const trackedLinks = selectAllWithBase( node, `a[href*='${location.hostname.split(".").slice(-2).join(".")}/l.php?']`, ); for (const a of trackedLinks) { const newHref = new URL(a.href).searchParams.get("u"); cleanLink(a, newHref); log(`Removed tracking from redirect link: ${a}`); } return trackedLinks.length; } const fbclidFallback = /((?:[?&]|%3F|%26)fbclid=.*?)($|[?&]|%3F|%26)/gi; function stripFBCLID(node) { const trackedLinks = selectAllWithBase(node, `a[href*='fbclid='i]`); for (const a of trackedLinks) { const link = new URL(a.href); link.searchParams.delete("fbclid"); if (a.href === link.href) { link.href = link.href.replace(fbclidFallback, "$2"); } if (a.href === link.href) { log(`Failed to remove fbclid from link:\n -> ${a}`); } else { a.href = link.href; applyStyle(a); log(`Removed fbclid from link: ${a}`); } } return trackedLinks.length; } /** @param {Element} node */ function stripRefs(node) { let intLinks = 0; /** @param {HTMLAnchorElement} a */ function _strip(a) { if (a.nodeName !== "A" || !domains.some(d => a.hostname.endsWith(d))) return; ++intLinks; applyEventBlockers(a.parentNode); delete a.dataset.ft; const linkBase = a.origin + a.pathname; if (a.hasAttribute("href")) { const orig = a.getAttribute("href"); // get unexpanded value const href = cleanLinkParams(orig, linkBase); // Don't assign here to avoid infinite mutation recursion if (href !== orig) { a.href = href; applyStyle(a); log(`Cleaned internal href:\n\t${orig}\n\t${a.getAttribute("href")}`); } } if (a.hasAttribute("ajaxify")) { const orig = a.getAttribute("ajaxify"); a.setAttribute("ajaxify", cleanLinkParams(orig, linkBase)); if (orig !== a.getAttribute("ajaxify")) { applyStyle(a); log(`Cleaned internal ajaxify link:\n\t${orig}\n\t${a.getAttribute("ajaxify")}`); } } if (a.dataset.hovercard) { delete a.dataset.hovercardReferrer; const orig = a.dataset.hovercard; a.dataset.hovercard = cleanLinkParams(orig, linkBase); if (orig !== a.dataset.hovercard) { applyStyle(a); log(`Cleaned internal hovercard link:\n\t${orig}\n\t${a.dataset.hovercard}`); } } } _strip(node); for (const a of node.getElementsByTagName("a")) { _strip(a); } return intLinks; } function fixGifs(node) { const gifs = selectAllWithBase(node, "div._5b-_"); for (const g of gifs) { const target = g.closest("div._2lhm"); if (!target) continue; const gif = target.querySelector("img.img").cloneNode(false); gif.classList.add("FBTR-SAFE"); gif.dataset.placeholder = gif.src; gif.dataset.src = g.parentNode.href; const controls = target.querySelector("div._393-").parentNode.cloneNode(true); controls.classList.add("FBTR-SAFE"); const toggle = e => { gif.src = controls.classList.toggle("fbtrHide") ? gif.dataset.src : gif.dataset.placeholder; stopPropagation(e); }; gif.addEventListener("click", toggle, true); controls.addEventListener("click", toggle, true); const wrapper = document.createElement("div"); wrapper.appendChild(gif); wrapper.appendChild(controls); for (const c of target.classList) wrapper.classList.add(c); target.parentNode.replaceChild(wrapper, target); log(`Fixed GIF: ${gif.dataset.src}`); } } /** @param {string} s */ function extractQuotedString(s) { return s.substring(s.indexOf('"') + 1, s.lastIndexOf('"')); } ================================================ FILE: src/content_script/content_script.js ================================================ import(browser.runtime.getURL("src/content_script/app.js")).catch(e => console.warn(`Failed to load FacebookTrackingRemoval: ${e}`), ); ================================================ FILE: src/content_script/dom.js ================================================ /** * Copyright (C) 2023-2024 Michael Ziminsky (Z) * * This file is part of FacebookTrackingRemoval. * * FacebookTrackingRemoval is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * FacebookTrackingRemoval is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with FacebookTrackingRemoval. If not, see . */ import { log } from "../common.js"; import { click_whitelist } from "../config.js"; import { COLLAPSED_SELECTOR, PROCESSED_CLASS } from "../consts.js"; export { applyEventBlockers, ariaText, buildCollapsible, cleanAttrs, inlineUse, selectAllWithBase, stopPropagation, visibleText, }; /** @param {Event} e */ function isAllowedTarget(e) { let checkTarget = e.target; // Walk through event target and parents until the currentTarget looking for an element that clicks are allowed on while (e.currentTarget.parentNode !== checkTarget) { const role = checkTarget.attributes.role; if (checkTarget.tagName === "A" && checkTarget.hostname === location.hostname) { return true; } if (role && click_whitelist.roles.includes(role.value.toUpperCase())) { return true; } if ( click_whitelist.elements.includes(checkTarget.tagName) || checkTarget.classList.contains("FBTR-SAFE") || checkTarget.matches(click_whitelist.selector) ) { return true; } checkTarget = checkTarget.parentNode; } return false; } /** * Meant to be used as a capturing event handler * @param {Event} e */ function restrictEventPropagation(e) { if (isAllowedTarget(e)) { log(`Allowed propagation of ${e.type} from ${e.target} to ${e.currentTarget}`); } else { stopPropagation(e); } } /** @param {Event} e */ function stopPropagation(e) { e.stopImmediatePropagation(); e.stopPropagation(); log(`Stopped propagation of ${e.type} from ${e.target}`); } /** @param {HTMLElement} target */ function applyEventBlockers(target) { target.addEventListener("mousedown", restrictEventPropagation, true); target.addEventListener("focusin", stopPropagation, true); target.addEventListener("focus", restrictEventPropagation, true); target.addEventListener("click", restrictEventPropagation, true); target.addEventListener("mouseup", restrictEventPropagation, true); target.addEventListener("focusout", stopPropagation, true); target.addEventListener("blur", stopPropagation, true); } /** @param {Element} elem */ function cleanAttrs(elem) { for (let i = elem.attributes.length - 1; i >= 0; --i) { const attr = elem.attributes[i]; if (attr.name !== "class" && !attr.name.startsWith("aria-")) elem.removeAttribute(attr.name); } } /** @param {string} label */ function buildCollapsible(label) { const content = document.createElement("summary"); content.textContent = label; content.classList.add("fbtrLabel"); const collapsible = document.createElement("details"); collapsible.classList.add(PROCESSED_CLASS); collapsible.classList.add(COLLAPSED_SELECTOR.substring(1)); collapsible.appendChild(content); return collapsible; } /** * @param {Element} node * @param {string} selector */ function selectAllWithBase(node, selector) { const nodeMatches = !node.classList.contains(PROCESSED_CLASS) && node.matches(selector); const childResults = []; for (const c of node.querySelectorAll(selector)) { if (!c.classList.contains(PROCESSED_CLASS)) childResults.push(c); } const results = (function* () { if (nodeMatches) yield node; yield* childResults; })(); results.length = childResults.length + nodeMatches; return results; } /** * Replace all `use` elements with a copy of their referenced content. * @param {Element} target */ function inlineUse(target) { for (const use of selectAllWithBase(target, "use")) { const used = document.querySelector(use.href.baseVal)?.cloneNode(true); if (used) { used.removeAttribute("id"); use.replaceWith(used); } } } /** @param {HTMLElement} elem */ function ariaText(elem) { const labels = elem .getAttribute("aria-labelledby") ?.split(" ") .map(id => document.getElementById(id)) .filter(e => e); const text = [...new Set(labels || [])].map(e => e.textContent).join(" "); return text ? text : elem.getAttribute("aria-label"); } /** @param {HTMLElement} elem */ function visibleText(elem) { let text = elem.dataset.content ?? ""; const bounds = elem.getBoundingClientRect(); const children = [...elem.childNodes].reverse(); while (children.length > 0) { const child = children.pop(); switch (child.nodeType) { case Node.TEXT_NODE: text += child.nodeValue; break; case Node.ELEMENT_NODE: { if (!rectsIntersect(bounds, child.getBoundingClientRect())) continue; text += child.dataset.content ?? ""; for (let c = child.lastChild; c !== null; c = c.previousSibling) children.push(c); break; } } } return text; } /** * @param {DOMRect} a * @param {DOMRect} b */ function rectsIntersect(a, b) { return a.top < b.bottom && a.right > b.left && a.bottom > b.top && a.left < b.right; } ================================================ FILE: src/i18n.js ================================================ // Copyright (C) 2021-2024 Michael Ziminsky (Z) // // This file is part of FacebookTrackingRemoval, originally from ProxyTab. // // FacebookTrackingRemoval is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // FacebookTrackingRemoval is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with FacebookTrackingRemoval. If not, see . /** * @see {@link browser.i18n.getMessage} * @param {string} key */ function getMessage(key, ...vars) { const msg = browser.i18n.getMessage(key, vars); if (!msg) throw `!! Missing Translation - ${key} !!`; return msg; } function getMessageSafe(key, ...vars) { try { return getMessage(key, ...vars); } catch (e) { return e; } } /** * Applies translations declared via attributes to elem * @param {HTMLElement} elem */ function translate(elem) { try { const { i18n: key, i18nAttr: attr = "title", i18nVars: vars = "" } = elem.dataset; elem.setAttribute(attr, getMessage(key, ...vars.split("||"))); } catch (e) { console.warn("Failed to apply translation to %o:", elem, e); } } window.customElements.define( "fbtr-i18n", class extends HTMLElement { static get observedAttributes() { return ["key"]; } constructor() { super(); for (const child of this.childNodes) { if (child.nodeName !== "PARAM") child.remove(); } // NOTE: Shadow DOM plays poorly with accessibility this.text = this.attachShadow({ mode: "open" }); this.observer = new MutationObserver(this.update.bind(this)); } get textContent() { return this.text.textContent; } attributeChangedCallback() { this.update(); } connectedCallback() { this.observer.observe(this, { childList: true, subtree: true, attributeFilter: ["value"] }); } disconnectedCallback() { this.observer.disconnect(); } update() { const key = this.getAttribute("key"); const vars = [...this.getElementsByTagName("param")].map(v => v.value); try { this.text.innerHTML = getMessage(key, ...vars); this.classList.remove("error"); } catch (e) { this.text.textContent = e; this.classList.add("error"); } } }, ); const I18N_SELECTOR = "[data-i18n]"; document.querySelectorAll(I18N_SELECTOR).forEach(translate); new MutationObserver(muts => { for (const m of muts) { if (m.type === "attributes") { translate(m.target); } else for (const e of m.addedNodes) { if (e.nodeType !== 1) continue; if (e.matches(I18N_SELECTOR)) translate(e); e.querySelectorAll(I18N_SELECTOR).forEach(translate); } } }).observe(document, { attributeFilter: ["data-i18n", "data-i18n-attr", "data-i18n-vars"], subtree: true, }); export default getMessageSafe; ================================================ FILE: src/options/options.css ================================================ @import url(./theme.css); /* Fallback for Chrome */ @import url(chrome://global/skin/in-content/common.css); /* Actual theme in FF */ :root { --reset-btn-size: 16px; } *, *:before, *:after { box-sizing: border-box; } #preview { white-space: nowrap; } #btnRefresh.ctrl::before { content: "Force "; } #_hideMethod > span { display: flex; gap: 1.5rem; } .hidden { display: none; } /* Make checkboxes visible from page action popup */ input { display: initial !important; } input[type="radio"] { margin-inline: initial; } body { width: max-content; } ul { list-style: none; padding-inline-start: calc(1.5 * var(--reset-btn-size)); } li { margin: 10px; position: relative; } li, label { display: flex; column-gap: 5px; align-items: center; } .flex-col { flex-direction: column; flex-grow: 1; align-items: initial; row-gap: 5px; } textarea { display: block; resize: vertical; padding-right: calc(1.5 * var(--reset-btn-size)); min-height: 2rem; flex-grow: 1; } details { padding: 5px; border: inset 1px; } details ul { padding-inline-start: 0; } details>summary { cursor: pointer; } btn-reset { position: absolute; cursor: pointer; height: var(--reset-btn-size); } btn-reset:first-child { left: calc(-1.5 * var(--reset-btn-size)); } btn-reset:last-child { top: calc(.5 * var(--reset-btn-size)); right: calc(.5 * var(--reset-btn-size)); } @media (prefers-color-scheme: dark) { btn-reset { filter: invert(); } } /* Timer */ .resetDone { animation: blank 1s 1; } @keyframes blank {} .resetDone btn-reset { animation: spin .5s linear infinite; } @keyframes spin { to { transform: rotate(360deg); } } li.resetDone { animation: outline .25s alternate ease-in-out 4; } @keyframes outline { to { outline: dotted 2px seagreen; } } ================================================ FILE: src/options/options.html ================================================

****


================================================ FILE: src/options/options.js ================================================ /* This file is part of FacebookTrackingRemoval. FacebookTrackingRemoval is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. FacebookTrackingRemoval is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with FacebookTrackingRemoval. If not, see . Copyright (C) 2016-2024 Michael Ziminsky */ import { isChrome } from "../common.js"; import * as config from "../config.js"; import { CHROME_PORT, MSG, NOOP, RATE_LIMIT } from "../consts.js"; import getMessageSafe from "../i18n.js"; import { timeoutRemaining } from "../rules_sync.js"; // /** @type {browser.runtime.Port} */ let bgPort; if (isChrome) bgPort = browser.runtime.connect({ name: CHROME_PORT }); /** @type {Options} */ const changes = new Proxy( {}, { set(obj, key, val) { if (config.options[key] === val) { delete obj[key]; } else { // Force undefined to null. undefined values don't get sent by postMessage obj[key] = val ?? null; } if (bgPort) bgPort.postMessage(obj); return true; }, }, ); // Only works in FF... https://bugs.chromium.org/p/chromium/issues/detail?id=31262 window.addEventListener("unload", () => { if (Object.keys(changes).length) Object.assign(config.options, changes); }); // Expert Options const modStyle = document.getElementById("modStyle"); const preview = document.getElementById("preview"); // Set version text document.title = `${getMessageSafe("optsTitle")} - v${browser.runtime.getManifest().version}`; document.getElementById("legend").append(` - v${browser.runtime.getManifest().version}`); { const userRules = document.getElementById("userRules"); userRules.title = getMessageSafe("optsUserRulesHover"); userRules.placeholder = getMessageSafe("optsUserRulesPlaceholder"); } // Set max value for sensitivity slider { const slider = document.getElementById("canvasSensitivity"); slider.max = config.MAX_CANVAS_SENSITIVITY; slider.title = getMessageSafe("optsSenseHover"); } /** @param {Event} e */ function handleChange(e) { switch (e.target.type) { case "checkbox": changes[e.target.id] = e.target.checked; break; case "radio": changes[e.target.name] = e.target.value; break; case "text": case "textarea": e.target.value = e.target.value.trim(); if (!e.target.value) { changes[e.target.id] = undefined; } else { changes[e.target.id] = e.target.value; } break; default: changes[e.target.id] = e.target.value; break; } } for (const text of document.querySelectorAll("input,textarea")) { text.addEventListener("change", handleChange); } document .getElementById("reset") .addEventListener("click", _ => config.reset().then(() => document.body.classList.add("resetDone"))); modStyle.addEventListener("input", e => (preview.style.cssText = e.target.value)); /** @param {Event} e */ function handleToggle(e) { document.getElementById(e.target.dataset.toggle).classList.toggle("hidden", !e.target.checked); } /** * @param {Element} elem * @param {string} name * @param {*} value */ function findRadio(elem, name, value) { return elem.querySelector(`input[name=${name}][value=${value}]`); } // Per-option reset functionality window.customElements.define( "btn-reset", class extends HTMLElement { constructor() { super(); const img = this.attachShadow({ mode: "open" }).appendChild(document.createElement("img")); img.src = "reset.svg"; img.alt = getMessageSafe("optsResetAlt"); img.title = getMessageSafe("optsResetTitle"); this.addEventListener("click", this.reset.bind(this)); } /** @param {MouseEvent} e */ reset(e) { e?.preventDefault(); const option = this.parentNode.querySelector("input[id],textarea[id],input[name]"); const key = option.id || option.name; changes[key] = null; switch (option.type) { case "radio": findRadio(this.parentNode, key, config.defaults[key]).checked = true; break; case "checkbox": option.checked = config.defaults[key]; break; default: option.value = config.defaults[key]; break; } this.parentNode.classList.add("resetDone"); } }, ); document.body.addEventListener("animationend", e => e.target.classList.remove("resetDone")); // Refresh button { const btnRefresh = document.getElementById("btnRefresh"); const btnText = getMessageSafe("optsRefresh"); btnRefresh.title = browser.i18n.getMessage("optsRefreshHover", [RATE_LIMIT / 1000 / 60]); let timer; let disabled = false; const resetBtn = () => { clearInterval(timer); timer = null; btnRefresh.textContent = btnText; btnRefresh.disabled = disabled = false; }; const btnRefreshTimer = () => { resetBtn(); timeoutRemaining().then((timeout = 0) => { if (timeout <= 0) return; let remaining = Math.ceil(timeout / 1000); btnRefresh.disabled = disabled = true; btnRefresh.textContent = `${btnText} - ${remaining--} seconds`; timer = setInterval(() => { if (remaining <= 0) { resetBtn(); } else { btnRefresh.textContent = `${btnText} - ${remaining--} seconds`; } }, 1000); }); }; btnRefreshTimer(); btnRefresh.addEventListener("click", e => { btnRefresh.disabled = disabled = true; btnRefresh.classList.remove("ctrl"); browser.runtime.sendMessage({ msg: MSG.rulesRefresh, force: e.ctrlKey }).then(btnRefreshTimer).catch(NOOP); }); window.addEventListener("keydown", e => { if (!e.repeat && e.key === "Control") { btnRefresh.classList.add("ctrl"); btnRefresh.disabled = false; } }); window.addEventListener("keyup", e => { if (e.key === "Control") { btnRefresh.classList.remove("ctrl"); btnRefresh.disabled = disabled; } }); } // Keep in sync with other options pages config.onChanged.addListener(init); // Avoid duplicated event listeners const dependFuncs = new Map(); function init() { for (const key in changes) { delete changes[key]; } const opts = config.options; for (const key in opts) { const value = opts[key]; const item = document.getElementById(key); if (item) { if (item.type === "checkbox") { item.checked = value; } else if (item.type === "text" || item.tagName === "TEXTAREA") { if (!item.placeholder) item.placeholder = config.defaults[key]; item.value = value; } else { item.value = value; } } else { const radio = findRadio(document, key, value); if (radio) radio.checked = true; } } preview.style.cssText = modStyle.value; for (const elem of document.querySelectorAll("[data-depends]")) { const source = document.getElementById(elem.dataset.depends); if (!dependFuncs.has(elem)) dependFuncs.set(elem, () => (elem.disabled = !source.checked)); source.addEventListener("change", dependFuncs.get(elem)); elem.disabled = !source.checked; } for (const checkbox of document.querySelectorAll("input[data-toggle]")) { checkbox.addEventListener("change", handleToggle); handleToggle.call(undefined, { target: checkbox }); } } config.READY.then(init); ================================================ FILE: src/options/theme.css ================================================ /* Relevant theme values taken from FF for use in chrome. Will be overridden by actual theme in FF */ :root { font: message-box; appearance: none; background-color: var(--in-content-page-background); color: var(--in-content-page-color); } body { font-size: 15px; font-weight: normal; margin: 0; } button, select, input[type='color'] { appearance: none; min-height: 32px; color: var(--in-content-button-text-color); border: 1px solid var(--in-content-button-border-color); border-radius: 4px; background-color: var(--in-content-button-background); font-weight: 400; padding: 7px 15px; text-decoration: none; margin: 4px 8px; font-size: 1em; } input:is([type='email'], [type='tel'], [type='text'], [type='password'], [type='url'], [type='number']), textarea { appearance: none; border: 1px solid var(--in-content-box-border-color); border-radius: 4px; color: inherit; background-color: var(--in-content-box-background); } :disabled { opacity: 0.4; } :host, :root { --in-content-page-color: rgb(21, 20, 26); --in-content-page-background: #fff; --in-content-text-color: var(--in-content-page-color); --in-content-deemphasized-text: rgb(91, 91, 102); --in-content-box-background: #fff; --in-content-box-background-odd: rgba(12, 12, 13, 0.05); /* grey 90 a05 */ --in-content-box-border-color: color-mix(in srgb, currentColor 41%, transparent); --in-content-box-info-background: #f0f0f4; --in-content-item-hover: color-mix(in srgb, var(--in-content-primary-button-background) 20%, transparent); --in-content-item-hover-text: var(--in-content-page-color); --in-content-item-selected: var(--in-content-primary-button-background); --in-content-item-selected-text: var(--in-content-primary-button-text-color); --in-content-icon-color: rgb(91, 91, 102); --in-content-accent-color: var(--in-content-primary-button-background); --in-content-accent-color-active: var(--in-content-primary-button-background-hover); --in-content-border-hover: var(--grey-90-a50); --in-content-border-invalid: var(--red-50); --in-content-border-color: #d7d7db; --in-content-error-text-color: #c50042; --in-content-link-color: var(--in-content-primary-button-background); --in-content-link-color-hover: var(--in-content-primary-button-background-hover); --in-content-link-color-active: var(--in-content-primary-button-background-active); --in-content-link-color-visited: var(--in-content-link-color); /* button background states are also used for checkboxes and radiobuttons */ --in-content-button-text-color: var(--in-content-text-color); --in-content-button-text-color-hover: var(--in-content-text-color); --in-content-button-text-color-active: var(--in-content-button-text-color-hover); --in-content-button-background: rgba(207, 207, 216, 0.33); --in-content-button-background-hover: rgba(207, 207, 216, 0.66); --in-content-button-background-active: rgb(207, 207, 216); --in-content-button-border-color: transparent; --in-content-button-border-color-hover: transparent; --in-content-button-border-color-active: var(--in-content-button-border-color-hover); --in-content-primary-button-text-color: rgb(251, 251, 254); --in-content-primary-button-text-color-hover: var(--in-content-primary-button-text-color); --in-content-primary-button-text-color-active: var(--in-content-primary-button-text-color); --in-content-primary-button-background: #0061e0; --in-content-primary-button-background-hover: #0250bb; --in-content-primary-button-background-active: #053e94; --in-content-primary-button-border-color: transparent; --in-content-primary-button-border-hover: transparent; --in-content-primary-button-border-active: transparent; --in-content-danger-button-background: #e22850; --in-content-danger-button-background-hover: #c50042; --in-content-danger-button-background-active: #810220; --in-content-focus-outline-color: var(--in-content-primary-button-background); --in-content-focus-outline-width: 2px; --in-content-focus-outline-offset: 2px; --in-content-focus-outline-inset: calc(-1 * var(--in-content-focus-outline-width)); --in-content-focus-outline: var(--in-content-focus-outline-width) solid var(--in-content-focus-outline-color); --in-content-table-background: #f8f8fa; --in-content-table-border-color: var(--in-content-box-border-color); --in-content-table-header-background: var(--in-content-primary-button-background); --in-content-table-header-color: var(--in-content-primary-button-text-color); --in-content-sidebar-width: 240px; --dialog-warning-text-color: var(--red-60); --checkbox-border-color: var(--in-content-box-border-color); --checkbox-unchecked-bgcolor: var(--in-content-button-background); --checkbox-unchecked-hover-bgcolor: var(--in-content-button-background-hover); --checkbox-unchecked-active-bgcolor: var(--in-content-button-background-active); --checkbox-checked-bgcolor: var(--in-content-primary-button-background); --checkbox-checked-color: var(--in-content-primary-button-text-color); --checkbox-checked-border-color: transparent; --checkbox-checked-hover-bgcolor: var(--in-content-primary-button-background-hover); --checkbox-checked-active-bgcolor: var(--in-content-primary-button-background-active); --blue-40: #45a1ff; --blue-50: #0a84ff; --blue-60: #0060df; --grey-30: #d7d7db; --grey-60: #4a4a4f; --grey-90-a10: rgba(12, 12, 13, 0.1); --grey-90-a20: rgba(12, 12, 13, 0.2); --grey-90-a30: rgba(12, 12, 13, 0.3); --grey-90-a50: rgba(12, 12, 13, 0.5); --grey-90-a60: rgba(12, 12, 13, 0.6); --green-50: #30e60b; --green-60: #12bc00; --green-70: #058b00; --green-80: #006504; --green-90: #003706; --orange-50: #ff9400; --red-40: #ff4f5e; --red-50: #ff0039; --red-60: #d70022; --red-70: #a4000f; --red-80: #5a0002; --red-90: #3e0200; --yellow-50: #ffe900; --yellow-60: #d7b600; --yellow-60-a30: rgba(215, 182, 0, 0.3); --yellow-70: #a47f00; --yellow-80: #715100; --yellow-90: #3e2800; --shadow-10: 0 1px 4px var(--grey-90-a10); --shadow-30: 0 4px 16px var(--grey-90-a10); --card-padding: 16px; --card-shadow: var(--shadow-10); --card-outline-color: var(--grey-30); --card-shadow-hover: var(--card-shadow), 0 0 0 5px var(--card-outline-color); accent-color: var(--in-content-accent-color); color-scheme: light dark; } @media (prefers-color-scheme: dark) { :host, :root { --in-content-page-background: rgb(28, 27, 34); --in-content-page-color: rgb(251, 251, 254); --in-content-deemphasized-text: rgb(191, 191, 201); --in-content-box-background: rgb(35, 34, 43); --in-content-box-background-odd: rgba(249, 249, 250, 0.05); --in-content-box-info-background: rgba(249, 249, 250, 0.15); --in-content-border-color: rgba(249, 249, 250, 0.2); --in-content-border-hover: rgba(249, 249, 250, 0.3); --in-content-border-invalid: rgb(255, 132, 139); --in-content-error-text-color: #ff9aa2; --in-content-button-background: rgb(43, 42, 51); --in-content-button-background-hover: rgb(82, 82, 94); --in-content-button-background-active: rgb(91, 91, 102); --in-content-icon-color: rgb(251, 251, 254); --in-content-primary-button-text-color: rgb(43, 42, 51); --in-content-primary-button-background: rgb(0, 221, 255); --in-content-primary-button-background-hover: rgb(128, 235, 255); --in-content-primary-button-background-active: rgb(170, 242, 255); --in-content-danger-button-background: #ff848b; --in-content-danger-button-background-hover: #ffbdc5; --in-content-danger-button-background-active: #ffdfe7; --in-content-table-background: rgb(35, 34, 43); --card-outline-color: var(--grey-60); --dialog-warning-text-color: var(--red-40); scrollbar-color: rgba(249, 249, 250, 0.4) rgba(20, 20, 25, 0.3); } } @media (prefers-contrast) { :host, :root { --in-content-page-color: CanvasText; --in-content-page-background: Canvas; --in-content-deemphasized-text: GrayText; --in-content-box-background: -moz-Dialog; --in-content-box-background-odd: -moz-Dialog; --in-content-box-border-color: -moz-DialogText; --in-content-box-info-background: -moz-Dialog; --in-content-item-hover: SelectedItem; --in-content-item-hover-text: SelectedItemText; --in-content-item-selected: SelectedItem; --in-content-item-selected-text: SelectedItemText; --in-content-icon-color: -moz-DialogText; --in-content-accent-color: SelectedItem; --in-content-accent-color-active: SelectedItem; --in-content-border-hover: ThreeDShadow; /* This is not great, but there is no suitable keyword for this. * In theory, we shouldn't be conveying invalid state just with a colour * change... */ --in-content-border-invalid: ThreeDShadow; --in-content-border-color: ThreeDShadow; --in-content-link-color: -moz-nativehyperlinktext; --in-content-link-color-hover: -moz-nativehyperlinktext; --in-content-link-color-active: -moz-nativehyperlinktext; --in-content-link-color-visited: -moz-nativehyperlinktext; --in-content-button-text-color: ButtonText; --in-content-button-text-color-hover: SelectedItemText; --in-content-button-text-color-active: SelectedItem; --in-content-button-background: ButtonFace; --in-content-button-background-hover: SelectedItem; --in-content-button-background-active: SelectedItemText; --in-content-button-border-color: ButtonText; --in-content-button-border-color-hover: SelectedItemText; --in-content-button-border-color-active: SelectedItem; --in-content-primary-button-text-color: ButtonFace; --in-content-primary-button-text-color-hover: SelectedItemText; --in-content-primary-button-text-color-active: SelectedItem; --in-content-primary-button-background: ButtonText; --in-content-primary-button-background-hover: SelectedItem; --in-content-primary-button-background-active: SelectedItemText; --in-content-primary-button-border-color: ButtonFace; --in-content-primary-button-border-hover: SelectedItemText; --in-content-primary-button-border-active: SelectedItem; --in-content-danger-button-background: var(--in-content-primary-button-background); --in-content-danger-button-background-hover: var(--in-content-primary-button-background-hover); --in-content-danger-button-background-active: var(--in-content-primary-button-background-active); --in-content-focus-outline-color: -moz-DialogText; --in-content-table-border-color: ThreeDDarkShadow; --in-content-table-background: -moz-Dialog; --in-content-table-header-background: -moz-Dialog; --in-content-table-header-color: -moz-DialogText; --dialog-warning-text-color: -moz-FieldText; --checkbox-border-color: ThreeDShadow; --checkbox-unchecked-bgcolor: -moz-Field; --checkbox-unchecked-hover-bgcolor: -moz-Field; --checkbox-unchecked-active-bgcolor: -moz-Field; --checkbox-checked-bgcolor: SelectedItem; --checkbox-checked-color: SelectedItemText; --checkbox-checked-border-color: SelectedItem; --checkbox-checked-hover-bgcolor: -moz-Field; --checkbox-checked-active-bgcolor: -moz-Field; } } @media not (prefers-contrast) { button.semi-transparent:not(.ghost-button, .primary):enabled { background-color: color-mix(in srgb, currentColor 10%, transparent); } button.semi-transparent:not(.primary):enabled:hover { background-color: color-mix(in srgb, currentColor 20%, transparent); } button.semi-transparent:not(.primary):enabled:hover:active { background-color: color-mix(in srgb, currentColor 30%, transparent); } } ================================================ FILE: src/rules_sync.js ================================================ /* This file is part of FacebookTrackingRemoval. FacebookTrackingRemoval is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. FacebookTrackingRemoval is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with FacebookTrackingRemoval. If not, see . Copyright (C) 2016-2024 Michael Ziminsky */ import { NOOP, RATE_LIMIT } from "./consts.js"; import { joinSelectors, parseHideRules, splitLines, stripComments } from "./util.js"; export { refreshRules, timeoutRemaining }; const SELECTOR_RULE_FILES = ["article_wrapper", "unconditional"]; const DYN_RULE_FILES = ["pending"]; const SPLIT_RULE_DIRS = ["sponsored", "suggested"]; const PARAM_CLEANING_FILES = ["params", "prefix_patterns", "values"]; const CLICK_WHITELIST_FILES = ["elements", "roles", "selectors"]; async function fetchRule(path, currentVal) { const devMode = (await browser.management.getSelf()).installType === "development"; return fetch(`https://${devMode ? "localhost" : "mgziminsky.gitlab.io"}/FacebookTrackingRemoval/${path}`, { mode: "cors", signal: devMode ? AbortSignal.timeout(100) : undefined, }) .then(resp => (resp.ok ? resp : Promise.reject())) .catch(() => currentVal ? Promise.reject(`Keeping current value: ${currentVal}`) : fetch(browser.runtime.getURL(`data/${path}`)), ) // Fallback to bundled copy .then(resp => (resp.ok ? resp.text() : Promise.reject())); } async function loadHideRules() { const { hide_rules: currentRules = {} } = await browser.storage.local.get("hide_rules"); const newRules = {}; for (const file of SELECTOR_RULE_FILES) { await fetchRule(`hide_rules/${file}`, currentRules[file]) .then(joinSelectors) .then(sel => (newRules[file] = sel)) .catch(e => console.warn(`Failed to load selectors file "${file}"\n\t`, e)); } for (const file of DYN_RULE_FILES) { await fetchRule(`hide_rules/${file}`, currentRules[file]) .then(parseHideRules) .then(rule => Object.assign((newRules[file] ??= {}), rule)) .catch(e => console.warn(`Failed to load legacy rules from "${file}"\n\t`, e)); } for (const dir of SPLIT_RULE_DIRS) { await loadSplitRule(dir, currentRules[dir]) .then(rule => Object.assign((newRules[dir] ??= {}), rule)) .catch(e => console.warn(`Split rule "${dir}" failed to load\n\t`, e)); } return Object.assign(currentRules, newRules); } async function loadArrayData(key, files) { const { [key]: currentRules = {} } = await browser.storage.local.get(key); const newRules = {}; for (const file of files) { await fetchRule(`${key}/${file}`, currentRules[file]) .then(stripComments) .then(splitLines) .then(data => (newRules[file] = data)) .catch(e => console.warn(`Failed to load array data from "${key}/${file}"\n\t`, e)); } return Object.assign(currentRules, newRules); } /** @param {HideRule} currentRule */ async function loadSplitRule(dir, currentRule) { const rule = {}; rule.selector = await fetchRule(`hide_rules/${dir}/selectors`, currentRule?.selector) .then(joinSelectors) .catch(e => console.warn(`Failed to load selectors for "${dir}"\n\t`, e)); // Selector required, fail if missing or empty if (!rule.selector) return Promise.reject("Selector missing or empty"); await fetchRule(`hide_rules/${dir}/texts`, currentRule?.texts) .then(stripComments) .then(splitLines) .then(a => a.sort()) .then(texts => (rule.texts = texts)) .catch(e => console.warn(`Failed to load texts for "${dir}"\n\t`, e)); await fetchRule(`hide_rules/${dir}/patterns`, currentRule?.patterns) .then(stripComments) .then(splitLines) .then(a => a.sort()) .then(patterns => (rule.patterns = patterns)) .catch(e => console.warn(`Failed to load patterns for "${dir}"\n\t`, e)); return rule; } /** @param {Function} func */ async function _try(func, ...args) { try { return await func(...args); } catch (error) { console.warn(error); } } async function timeoutRemaining() { const { lastRuleRefresh } = await browser.storage.local.get("lastRuleRefresh"); const timeout = !lastRuleRefresh ? 0 : RATE_LIMIT - (Date.now() - Date.parse(lastRuleRefresh)); return Math.max(0, timeout); } async function refreshRules(force = false) { const timeout = force ? 0 : await timeoutRemaining(); if (timeout > 0) return Promise.reject(timeout); browser.storage.local .set({ hide_rules: await _try(loadHideRules), param_cleaning: await _try(loadArrayData, "param_cleaning", PARAM_CLEANING_FILES), click_whitelist: await _try(loadArrayData, "click_whitelist", CLICK_WHITELIST_FILES), lastRuleRefresh: new Date().toUTCString(), }) .then(() => RATE_LIMIT); } // refresh rules every 12 hours browser.alarms.onAlarm.addListener(() => refreshRules().catch(NOOP)); browser.alarms.create({ when: Date.now(), periodInMinutes: 60 * 12 }); ================================================ FILE: src/types.d.ts ================================================ // This file is just for the IDE to provide code-assist interface HideRule { selector: string; texts?: Map; patterns?: RegExp; } interface HideRules { article_wrapper: string; sponsored: HideRule; suggested: HideRule; pending: HideRule; } interface ParamCleaning { params: string[]; prefix_patterns: string[]; values: string[]; pattern: RegExp; } interface ClickWhitelist { elements: string[]; roles: string[]; selectors: string[]; selector: string; } interface Options { enabled: boolean; fixLinks: boolean; internalRefs: boolean; inlineVids: boolean; fixVideos: boolean; delPixeled: boolean; delSuggest: boolean; hideMethod: string; useStyle: boolean; logging: boolean; modStyle: string; userRules: string; pendingRules: boolean; testCanvas: boolean; canvasSensitivity: number; } ================================================ FILE: src/util.js ================================================ /* This file is part of FacebookTrackingRemoval. FacebookTrackingRemoval is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. FacebookTrackingRemoval is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with FacebookTrackingRemoval. If not, see . Copyright (C) 2016-2024 Michael Ziminsky */ import { param_cleaning } from "./config.js"; export { cleanLinkParams, joinSelectors, normalizeString, parseHideRules, splitLines, stripComments }; /** @param {string} text */ function splitLines(text) { return text.trim().split(/\s*$\s*/m); } /** @param {string} text */ function stripComments(text) { return text.replace(/\/\*.*?\*\//g, "").trim(); } /** @param {string} text */ function joinSelectors(text) { return stripComments(text) .replace(/\s*$\s/gm, ",") .replace(/\s+/g, " "); } function parseHideRules(text) { const selector = new Set(); const texts = new Set(); const patterns = new Set(); for (const line of splitLines(stripComments(text))) { const [sel, ...filters] = line.split("||"); sel.trim().replaceAll(/\s+/g, " ").split(",").forEach(selector.add.bind(selector)); for (const val of filters) { if (/^\/.*[^\\](?:\\\\)*\/$/.test(val)) patterns.add(val.substring(1, val.length - 1)); else texts.add(val); } } return { selector: Array.from(selector).join(","), texts: Array.from(texts).sort(), patterns: Array.from(patterns).sort(), }; } /** @param {string} str */ function normalizeString(str) { return Array.from(str.trim().toLowerCase()).sort().join(""); } /** @param {string} link */ function cleanLinkParams(link, base = location.origin + location.pathname) { try { // Don't mess with anchor links if (link.startsWith("#")) return link; const url = new URL(link, base); // Nothing to do if (url.search.length <= 1) return link; const cleanParams = new URLSearchParams(url.search); // Can't use bind in FF115+ due to addition of optional 2nd arg for matching on value const deleteParam = p => cleanParams.delete(p); /**@type {ParamCleaning}*/ const pc = param_cleaning; pc.params.forEach(deleteParam); // for..of loop stops early if items are removed // .keys() doesn't work in FF... https://bugzilla.mozilla.org/show_bug.cgi?id=1414602 [...cleanParams] .map(([key, _]) => key) .filter(pc.pattern.test.bind(pc.pattern)) .forEach(deleteParam); // Handle json encoded values for (const name of pc.values.filter(v => cleanParams.has(v))) { const val = JSON.parse(cleanParams.get(name)); for (const param of pc.params) delete val[param]; for (const key in val) { if (pc.pattern.test(key)) delete val[key]; } cleanParams.set(name, JSON.stringify(val)); } const origLength = url.search.length; url.search = cleanParams; return origLength === url.search.length ? link // No changes, avoid unintended modification : // If link is the same host, use absolute pathname, otherwise use full URL url.href.substring(url.host === location.host ? location.origin.length : 0); } catch (e) { return link; } }