Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Cypress 12.15.0] Failed to execute 'importScripts' on 'WorkerGlobalScope' #28400

Open
JrVillabona opened this issue Nov 24, 2023 · 10 comments
Open
Labels
prevent-stale mark an issue so it is ignored by stale[bot] stage: needs investigating Someone from Cypress needs to look at this type: regression A bug that didn't appear until a specific Cy version release v12.5.0 🐛

Comments

@JrVillabona
Copy link

JrVillabona commented Nov 24, 2023

Current behavior

We have been using the text-from-image package to extract text from images. This works using the Tesseract OCR engine. But since Cypress version 12.15.0 we have not been able to run tests using this package again. This has limited us to not being able to keep up to date with the latest versions of Cypress. We have had to stay parked in version 12.14.0.

When running any test, the execution fails on BEFORE ALL:

(uncaught exception)Error: Uncaught NetworkError: Failed to execute 'importScripts' on 'WorkerGlobalScope': The script at 'https://unpkg.com/[email protected]/dist/worker.min.js' failed to load.

Refused to load the script 'https://unpkg.com/[email protected]/dist/worker.min.js' because it violates the following Content Security Policy directive: "script-src 'unsafe-eval'". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.

Running Cypress test in v12.14 or earlier does not have this problem.

We have read the Changelog 12.15.0, particularly in relation to Experimental CSP Allow List but we have not been successful in resolving it.

This may be a related issue Cypress 12.15 broke the ability to run Web Workers in Cypress tests #27298

Desired behavior

The use of Tesseract OCR should be supported again without any problems, as it used to be before.

Test code to reproduce

Make sure to have installed or added to the package.json file:
"cypress": "^12.15.0"
"text-from-image": "^1.1.1"

Add to the cypress/support/commands.js file:
const ReadText = require('text-from-image')

Create a custom command to use the ReadText:

// This command takes an imageURL parameter and returns a promise
// that resolves to a six-digit confirmation number extracted from the proof-image.
Cypress.Commands.add(
	'getConfirmationNumberFromTamperProof',
	(imageURL) =>
		new Cypress.Promise((resolve, reject) => {
			ReadText(imageURL)
				.then((text) => {
					const confirmationNumber = text.replace(/[^0-9]/g, '').slice(-6)
					resolve(confirmationNumber)
				})
				.catch((err) => {
					reject(err)
				})
		})
)

Here is an example of how we're using the getConfirmationNumberFromProofImage custom command:

cy.get('[data-qa-id="confirmation-image"]')
		.first()
		.invoke('attr', 'src')
		.then((sourceImage) => {
			cy.getConfirmationNumberFromProofImage(sourceImage).then((confirmationNumber) => {
				cy.get('[data-qa-id="confirmation-code"]').type(confirmationNumber)
				cy.get('[data-qa-id="confirm-proof"]').click()
			})
		})

Cypress Version

12.15.0

Node version

18.4.0

Operating System

macOS 14.1

Debug Logs

No response

Other

This issue: Cypress 12.15 broke the ability to run Web Workers in cypress tests that was reported 4 months ago, reporting something similar, was fixed in this PR: fix: Fix web worker creation within spec frame maybe it is related.

It is worth noting that we have upgraded to the latest version of Cypress, and it still results in the same error.
No response

@jennifer-shehane jennifer-shehane added the stage: needs investigating Someone from Cypress needs to look at this label Nov 28, 2023
@burkedavid
Copy link

burkedavid commented Feb 8, 2024

Experiencing the same problem here on v13.6.2 Is there a workaround available ?

(uncaught exception)Error: Uncaught NetworkError: Failed to execute 'importScripts' on 'WorkerGlobalScope': The script at 'https://unpkg.com/[email protected]/dist/worker.min.js' failed to load.

@JrVillabona
Copy link
Author

JrVillabona commented Feb 14, 2024

Experiencing the same problem here on v13.6.2 Is there a workaround available ?

(uncaught exception)Error: Uncaught NetworkError: Failed to execute 'importScripts' on 'WorkerGlobalScope': The script at 'https://unpkg.com/[email protected]/dist/worker.min.js' failed to load.

@burkedavid No workaround found so far, still parked in the 12.14.0 version, how about you?

@burkedavid
Copy link

Have had to Park it also and remove it from package.json as started breaking other tests.

@jennifer-shehane jennifer-shehane added the type: regression A bug that didn't appear until a specific Cy version release label Feb 26, 2024
@Denhai
Copy link

Denhai commented May 16, 2024

My workaround is to swallow this error.
https://docs.cypress.io/api/cypress-api/catalog-of-events#Uncaught-Exceptions

Cypress.on('uncaught:exception', (err, runnable) => {
  if (err.message.match(`Uncaught NetworkError: Failed to execute 'importScripts' on 'WorkerGlobalScope'`)) {
    return false;
  }
  return true;
});

@cypress-app-bot
Copy link
Collaborator

This issue has not had any activity in 180 days. Cypress evolves quickly and the reported behavior should be tested on the latest version of Cypress to verify the behavior is still occurring. It will be closed in 14 days if no updates are provided.

@cypress-app-bot cypress-app-bot added the stale no activity on this issue for a long period label Nov 13, 2024
@JrVillabona
Copy link
Author

@jennifer-shehane Any update on this? I keep getting the same behavior

@ryanthemanuel ryanthemanuel added prevent-stale mark an issue so it is ignored by stale[bot] and removed stale no activity on this issue for a long period labels Nov 19, 2024
@tarasMarieiev
Copy link

The issue still persists. I tried using the native tesseract.js library in combination with a Cypress project, but the problem remains.

For now, I still need to stick with version 12.14.0.

Are there any updates on this issue? Will it be fixed soon?

Thanks!

@tarasMarieiev
Copy link

@jennifer-shehane sorry for pinging you again, do you have any updates around that?

@samtsai
Copy link
Contributor

samtsai commented Dec 11, 2024

Alternatively, you could install tesseract.js as an npm package and create a plugin:

import type Tesseract from "tesseract.js"
import { createWorker } from "tesseract.js"

interface Log {
  workerId: string
  status: string
  progress: number
  userJobId: string
}

export type Options = Partial<Tesseract.RecognizeOptions> & {
  doNotTerminate?: boolean
}

let localWorker: Tesseract.Worker | null = null

const initiateWorker = async () => {
  const worker = await createWorker("eng", undefined, {
    logger: (m: Log) => {
      if (m.progress > 0) {
        console.log(`OCR: ${m.status} (${m.progress * 100}%)`)
      }
    },
  })
  localWorker = worker
  return worker
}

const recognize = async ({
  url,
  options,
}: {
  url: string
  options?: Options
}) => {
  const { doNotTerminate, ...opts } = options ?? {}

  let worker = localWorker

  if (!worker) {
    worker = await initiateWorker()
  }

  try {
    const {
      data: { text },
    } = await worker.recognize(url, opts)
    if (!doNotTerminate && worker) {
      await worker.terminate()
    }
    return text
  } catch (e) {
    console.error(`Could not recognize text in image (${e.message})`)
    if (!doNotTerminate && worker) {
      await worker.terminate()
    }
    return ""
  }
}

const terminateWorker = async (worker?: Tesseract.Worker | null) => {
  worker = localWorker

  if (worker) {
    await worker.terminate()
  } else {
    console.warn("Worker is already terminated")
  }

  return null
}

export { initiateWorker, recognize, terminateWorker }

@tarasMarieiev
Copy link

tarasMarieiev commented Dec 11, 2024

I found the solution in installing the native tesseract.js and moving it to the Cypress task, which is executed in the Node.js environment instead of the browser. This approach does not enforce a browser-like CSP, so Tesseract.js can load its worker script without restrictions.

  1. npm install tesseract.js
  2. cypress.config.ts:
import tesseract from 'tesseract.js'
....
export default defineConfig({
  .......
  e2e: {
    ........
      on('task', {
        getImageText(imagePath) {
          return tesseract.recognize(imagePath, 'eng').then(({ data: { text } }) => text)
        }
      })
    },
  },
})
  1. use the task in your test:
it('parse data with improved error handling', () => {
    const screenshotName = 'test-screenshot'
    const screenshotPath =`cypress/screenshots/${screenshotName}.png`
     
     cy.get(<locator>)
      .screenshot(screenshotName,
      .then(() => {
             return cy.task('getImageText', screenshotPath).then((text) => {
                   cy.log(text)
                   <assertions>
              })
       })
  })

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
prevent-stale mark an issue so it is ignored by stale[bot] stage: needs investigating Someone from Cypress needs to look at this type: regression A bug that didn't appear until a specific Cy version release v12.5.0 🐛
Projects
None yet
Development

No branches or pull requests

8 participants