I’m getting a TrustedScript error while trying to load jQuery into a page using Puppeteer. The error message says the document needs TrustedScript assignment.
I’ve tried different approaches to add the script:
// Method 1: Using CDN URL
await browser.addScriptTag({url: "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"});
// Method 2: Local file path
await browser.addScriptTag({path: "./scripts/jquery.min.js"});
// Method 3: Direct content
await browser.addScriptTag({content: jqueryLibrary});
All these methods trigger the same TrustedScript error. Has anyone found a working solution to inject jQuery or other libraries when this security policy is active?
I hit this exact problem last month with a client’s site that had strict CSP policies. The TrustedScript error happens because the page blocks arbitrary script injection through Content Security Policy restrictions. Here’s what fixed it for me: use page.setBypassCSP(true) before navigating and adding scripts. Call this right after creating the page instance but before page.goto(). This disables CSP enforcement for your Puppeteer session. Your existing addScriptTag methods should work fine after that. Just remember - this only affects the Puppeteer browser instance, not the actual website’s security for regular users.
You can also use page.addInitScript() before navigating. This injects the script into every frame before page scripts run, so it completely bypasses trusted types. Works way better than evaluate for jQuery since it loads before DOM ready.
Had the same problem with enterprise apps that use Trusted Types. Try using page.evaluate() instead of addScriptTag to run the script directly in the page context. Just fetch the jQuery source and inject it through evaluation - it’ll bypass those TrustedScript restrictions. Something like await page.evaluate(() => { /* jquery source code here */ }) works because it runs in the page’s execution context instead of trying to inject external scripts. This approach has been solid for me on sites with strict security policies where I couldn’t bypass CSP.