crawlee icon indicating copy to clipboard operation
crawlee copied to clipboard

parseWithCheerio iframe expansion fails on pages with Trusted Types CSP

Open nikitachapovskii-dev opened this issue 7 months ago • 2 comments

Issue description

https://github.com/apify/store-website-content-crawler/issues/699)

When crawling pages that enforce a Trusted Types Content Security Policy (e.g. Google Sheets published pages), parseWithCheerio silently fails to expand iframes and returns the page without their content.

The affected URL pattern: https://docs.google.com/spreadsheets/d/.../pubhtml

Root Cause

parseWithCheerio expands iframes by injecting their content into the browser DOM via frame.evaluate():

https://github.com/apify/crawlee/blob/fc39e1a51dfae1d8b3c3b25e1da213f8b9187c97/packages/playwright-crawler/src/internals/utils/playwright-utils.ts#L637

innerHTML is a Trusted Types sink. On pages with a strict Trusted Types policy, the browser blocks the assignment and throws:

TypeError: Failed to set the 'innerHTML' property on 'Element':
This document requires 'TrustedHTML' assignment.

The error is swallowed by the surrounding try/catch, so the iframe content is silently dropped.

Investigation

What was tested:

  • Attempted a patch using DOMParser.parseFromString as an alternative - also blocked:
  • Confirmed that any browser-side HTML string parsing is blocked by Google Sheets' CSP in Firefox

What works:

  • Playwright's Node.js API (iframe.locator('body').first().innerHTML(), frame.content()), these are not subject to browser CSP, they run server-side

Proposed Fix

Move page.content() and cheerio.load() before the iframe expansion block. Replace iframes in the Cheerio DOM on the Node.js side, never touching the browser DOM (packages/playwright-crawler/src/internals/utils/playwright-utils.ts):

  export async function parseWithCheerio(page, ignoreShadowRoots = false, ignoreIframes = false) {                                                                                                                                                                                                                                                                                                             
      ow(page, ow.object.validate(validators.browserPage));                                                                                                                                                                                                                                                                                                                                                    
                                                                                                                                                                                                                                                                                                                                                                                                               
      // Get page HTML first — Node.js side, not subject to browser CSP                                                                                                                                                                                                                                                                                                                                        
      const html = ignoreShadowRoots                                                                                                                                                                                                                                                                                                                                                                           
          ? null                                                                                                                                                                                                                                                                                                                                                                                               
          : ((await page.evaluate(`(${expandShadowRoots.toString()})(document)`)) as string);
      const pageContent = html || (await page.content());                                                                                                                                                                                                                                                                                                                                                      
      const $ = cheerio.load(pageContent);
                                                                                                                                                                                                                                                                                                                                                                                                               
      if (page.frames().length > 1 && !ignoreIframes) {     
          const frames = await page.$$('iframe');
          const cheerioIframes = $('iframe').toArray();                                                                                                                                                                                                                                                                                                                                                        
   
          await Promise.all(                                                                                                                                                                                                                                                                                                                                                                                   
              frames.map(async (frame, index) => {          
                  try {
                      const iframe = await frame.contentFrame();
                                                                                                                                                                                                                                                                                                                                                                                                               
                      if (iframe && cheerioIframes[index]) {
                          const getIframeHTML = async (): Promise<string> => {                                                                                                                                                                                                                                                                                                                                 
                              try {                         
                                  return iframe.locator('body').first().innerHTML();
                              } catch {                                                                                                                                                                                                                                                                                                                                                                        
                                  return iframe.content();
                              }                                                                                                                                                                                                                                                                                                                                                                                
                          };                                

                          const contents = await getIframeHTML();
                          $(cheerioIframes[index]).replaceWith(
                              `<div class="crawlee-iframe-replacement">${contents}</div>`,                                                                                                                                                                                                                                                                                                                     
                          );
                      }                                                                                                                                                                                                                                                                                                                                                                                        
                  } catch (error) {                         
                      log.warning(`Failed to extract iframe content: ${error}`);
                  }                                                                                                                                                                                                                                                                                                                                                                                            
              }),
          );                                                                                                                                                                                                                                                                                                                                                                                                   
      }                                                     

      return $;                                                                                                                                                                                                                                                                                                                                                                                                
  }

This approach was tested locally against the Google Sheets URL and produces correct output (full spreadsheet content extracted).

Concerns

Index-based iframe matching is fragile. page.$$('iframe') queries the live DOM while $('iframe').toArray() operates on a snapshot taken earlier. On highly dynamic pages this could cause a mismatch.

expandShadowRoots uses innerHTML internally and may also fail on pages with Trusted Types CSP — pre-existing issue, independent of this fix.

nikitachapovskii-dev avatar Apr 21 '26 09:04 nikitachapovskii-dev

Hey @janbuchar @barjin found one more issue CSP issue with iframe expansion, would love your input on the proposed fix and whether the index-based matching approach is the right direction.

nikitachapovskii-dev avatar Apr 21 '26 09:04 nikitachapovskii-dev

I agree with both your points and the concerns - i.e., the proposed fix looks logical to me, but the index-based approach is fragile (but this is perhaps not that much of an issue).

To be honest, I'd be fine marking this as wontfix, as Google Docs are infamous for doing weird JS / HTML things to put text editor / spreadsheet processor in the browser. parseWithCheerio is still just a helper function; perhaps for anything more advanced, the Crawlee users should figure out custom solutions (note that e.g. passing ?output=csv query param to the URL downloads the spreadsheet as CSV).

Anyway, I understand we need this in WCC soonish. Can you prepare a PR with the approach described in the issue @nikitachapovskii-dev ? Cheers!

barjin avatar Apr 22 '26 08:04 barjin