Home > Software design >  Is there a way to modify userAgent in Cypress to simulate mobile [2022] Chrome 100
Is there a way to modify userAgent in Cypress to simulate mobile [2022] Chrome 100

Time:07-13

when google introduced Chrome 100 they disabled possibility to modify userAgent string from for example Cypress tests.

We were using that technique to simulate that we are on mobile devices. For example:

cy.visit(`URL`, {
    onBeforeLoad: win => {
        Object.defineProperty(win.navigator, 'userAgent', {
           value: 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1',
                        });
                    },
                });

Changing viewport size is not the solution, cause in this case we need to really simulate user agent. Is there a way to do that programmatically since then?

CodePudding user response:

You can no longer alter the userAgent via .visit(). In order to modify the userAgent, you must pass it in as a argument via CLI. You can verify the userAgent is updated on the Settings tab of the test runner in open mode.

npx cypress open --userAgent="Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1"

  • Related