i have no control of the server. as a user i want to block the scripts from running…
- User
i have no control of the server. as a user i want to block the scripts from running without using "no js" globally with user script instead of writing another extension. would window.trustedTypes work? """ The createPolicy() method of the TrustedTypePolicyFactory interface creates a TrustedTypePolicy object that implements the rules passed as policyOptions.
The default policy In Chrome a policy with a name of "default" creates a special policy that will be used if a string (rather than a Trusted Type object) is passed to an injection sink. This can be used in a transitional phase while moving from an application that inserted strings into injection sinks.
Note: The above behavior is not yet settled in the specification and may change in future.
Warning: A lax default policy could defeat the purpose of using Trusted Types, and therefore should be defined with strict rules to ensure it cannot be used to run dangerous code.
createPolicy(policyName, policyOptions) Parameters policyName A string with the name of the policy.
policyOptions Optional User-defined functions for converting strings into trusted values.
createHTML(input[,args]) A callback function in the form of a string that contains code to run when creating a TrustedHTML object.
createScript(input[,args]) A callback function in the form of a string that contains code to run when creating a TrustedScript object.
createScriptURL(input[,args]) A callback function in the form of a string that contains code to run when creating a TrustedScriptURL object.
Return value A TrustedTypePolicy object.
Exceptions TypeError Thrown if policy names are restricted by the Content Security Policy trusted-types directive and this name is not on the allowlist.
TypeError Thrown if the name is a duplicate and the Content Security Policy trusted-types directive is not using allow-duplicates.
Examples The below code creates a policy with the name "myEscapePolicy" with a function defined for createHTML() which sanitizes HTML.
const escapeHTMLPolicy = trustedTypes.createPolicy("myEscapePolicy", { createHTML: (string) => string.replace(/</g, "<"), }); Creating a default policy On a site where Trusted Types are enforced via a Content Security Policy with the require-trusted-types-for directive set to script, any injection script that accepts a script expects a Trusted Type object. In the case that a string is inserted instead, the following default policy will be used.
The policy logs a message to the console to remind the developer to refactor this part of the application to use a Trusted Type object. It also appends details of the use of the default policy, type, and injection sink to the returned value.
trustedTypes.createPolicy("default", { createScriptURL: (s, type, sink) => { console.log("Please refactor."); return
${s}?default-policy-used&type=${encodeURIComponent( type, )}&sink=${encodeURIComponent(sink)}; }, }); """ - Assistant
Using
window.trustedTypescan help mitigate certain types of script injections by enforcing strict policies on how scripts are created and injected dynamically. However, it won't completely block all scripts from running on a page, especially those that are already present or execute as part of the initial page load. That said, if you want to limit or control dynamic script injections without globally disabling JavaScript or installing another extension, you can use a user script to define strict Trusted Types policies. Here's how you can approach this:Understanding Trusted Types
Trusted Types are a browser feature designed to help prevent Cross-Site Scripting (XSS) by restricting the ways in which scripts and other potentially dangerous content can be injected into the DOM. By defining policies, you can control or sanitize the content that's allowed to be injected.
Creating a Strict Trusted Types Policy
You can create a user script that establishes a strict Trusted Types policy to sanitize or block dynamic script creation. Here's an example of how you might do this:
javascript// ==UserScript== // @name Strict Trusted Types Policy // @namespace http://tampermonkey.net/ // @version 1.0 // @description Block or sanitize dynamic scripts using Trusted Types // @match *://*/* // @run-at document-start // @grant none // ==/UserScript== (function() { 'use strict'; if (window.trustedTypes) { try { // Create a strict policy that doesn't allow any scripts window.trustedTypes.createPolicy('strictPolicy', { createHTML: (input) => { // Sanitize or reject HTML as needed return ''; }, createScript: (input) => { // Reject scripts by throwing an error or returning a safe value throw new Error('Script injection blocked by Trusted Types policy.'); }, createScriptURL: (input) => { // Reject script URLs throw new Error('Script URL injection blocked by Trusted Types policy.'); } }); // Enforce the policy by setting default window.trustedTypes.policy = window.trustedTypes.createPolicy('default', { createHTML: () => '', createScript: () => { throw new Error('Scripts are blocked by default policy.'); }, createScriptURL: () => { throw new Error('Script URLs are blocked by default policy.'); } }); console.log('Strict Trusted Types policy has been applied.'); } catch (e) { console.error('Failed to apply Trusted Types policy:', e); } } else { console.warn('Trusted Types are not supported in this browser.'); } })();Explanation of the Script
-
Userscript Metadata:
@run-at document-start: Ensures the script runs as early as possible before other scripts on the page. This increases the likelihood that your policy is in place before any potentially malicious scripts execute.
-
Check for Trusted Types Support:
- The script first checks if the browser supports
window.trustedTypes. If not, it logs a warning.
- The script first checks if the browser supports
-
Create a Strict Policy:
- A policy named
'strictPolicy'is created with functions forcreateHTML,createScript, andcreateScriptURL. These functions either sanitize the input or throw errors to block untrusted content.
- A policy named
-
Enforce Default Policy:
- By setting a default policy, you make sure that any attempt to create scripts without using a Trusted Type object will be blocked.
-
Error Handling:
- Appropriate error messages are logged if the policy creation fails, providing insight into what might be going wrong.
Limitations
-
Initial Scripts: This approach won't prevent scripts that are part of the initial page load or already embedded in the HTML from running. Trusted Types mainly help with dynamically injected scripts.
-
Inline Event Handlers: Scripts executed via inline event handlers (e.g.,
onclick,onload) won't be blocked by Trusted Types. To handle these, you might need additional sanitization. -
Browser Support: Trusted Types are supported in modern browsers like Chrome and Edge but may not be available in all browsers.
Alternatives and Enhancements
-
Content Security Policy (CSP): While you mentioned not having server control, some user scripts can modify the CSP headers on the client side to restrict script execution further. However, this can be complex and might not work in all scenarios.
-
Mutation Observers: You can use Mutation Observers within your user script to monitor and remove or alter any new
<script>tags or event handlers added to the DOM after the initial load. -
Combination Approaches: Combining Trusted Types with other client-side measures (like Mutation Observers) can provide a more robust solution against unwanted scripts.
Final Thoughts
While using
window.trustedTypesin a user script is a clever way to add an extra layer of protection against dynamic script injections, it doesn't offer a complete solution for blocking all JavaScript execution. If your goal is to completely prevent scripts from running, disabling JavaScript globally or using dedicated extensions (like script blockers) would be more effective. However, if you're aiming to mitigate specific types of script injections without disabling JavaScript entirely, Trusted Types can be a valuable tool in your toolkit.If you decide to proceed with the
trustedTypesapproach, ensure you thoroughly test it on the websites you visit to confirm that it doesn't inadvertently break functionality you rely on. -