question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

DOMexception: Document is not focused

See original GitHub issue

Current behavior

Test case

For a programme we need to validate the correct processing of text in the DOM to a text blob copied to keyboard, for this we’ve built a test:

describe('..., () => {
  before(() => {
    cy.visitPage();
  });

  it('should open the logs', () => {
    cy.get('body')
      .type('{ctrl}{shift}`');
    cy.get('[data-cy="stubs-fake-logs-content"]')
      .contains(<check text>)
      .click();
  });

  it('should click on a log line', () => {
    cy.get('[data-cy="actions-table"]')
      .find('tr')
      .eq(1)
      .click();
  });

  it('should copy the response content', () => {
    cy.get('[data-cy="copySnippetButton-JSON"]')
      .click();
  });

  it('should validate the correct data was extracted', () => {
    cy.task('getClipboard')
      .should('contain', '"<key>": "<value>"');
    cy.task('getClipboard')
      .should('not.contain', 'ResponseData');
  });
});

The button that is clicked has some custom handling for the clipboard due to legacy browsers:

export const copyText = async text => {
  if (navigator.clipboard) {
    return navigator.clipboard.writeText(text);
  }

  const readOnlyTextArea = document.createElement('textarea');
  readOnlyTextArea.value = text;

  readOnlyTextArea.setAttribute('readonly', true);
  readOnlyTextArea.style.position = 'absolute';
  readOnlyTextArea.style.left = '-9001px';

  document.body.appendChild(readOnlyTextArea);

  readOnlyTextArea.select();
  document.execCommand('copy');

  document.body.removeChild(readOnlyTextArea);
};

Somehow in this clipboard handler the following error appears: Screenshot 2021-09-22 at 12 58 15

The tests may succeed X times, then suddenly the next run they all fail with the error above (which causes the assert on the clipboard contents to fail), from which Cypress cannot be restored until you restart it. This behaviour is not consistent and may take between 1-10 runs to show up, it also does not show up in production setting.

Desired behavior

Cypress should make sure the application DOM/window stays in focus within its test-runner such that the clipboard access functions (and other DOM related actions) do not display behaviour that is not seen in browsers.

Test code to reproduce

Provided above

Cypress Version

8.4.1

Other

No response

Issue Analytics

  • State:open
  • Created 2 years ago
  • Reactions:13
  • Comments:5

github_iconTop GitHub Comments

14reactions
momesanacommented, Jan 2, 2022

We have a similar problem. A Cypress test for a button which copies the currently selected value of a select component to the clipboard is flaky and fails about half of the time with the above message. This can also be reliably reproduced when running Cypress interactively, then opening the dev tools and making sure the dev tools window has focus for example by clicking into it while the mentioned test is running.

The error message does kind of make sense in that scenario as the dev tools window has grabbed the focus away from the actual test window running our application. But why that also occurs in headless mode where the dev tools aren’t active or the fact that it happens non-deterministically is something we can’t yet explain.

Common sense would dictate that somehow focusing the actual test window before clicking the copy button would fix the problem but this doesn’t work even though it can be verified that the window has been focused using cy.focused. After a fair amount of trial and error we came to the following solution:

  1. first focus the copy icon/button which is about to be clicked, then
  2. use cy.realClick from cypress-real-events instead of cy.click

Why that works, I can’t say. But only using cy.focus in combination with cy.click or solely relying on cy.realClick doesn’t yield the desired effect. With the combination however, I wasn’t able to reproduce the error in more than a dozen test runs but of course that may just be pure luck. Still, this is an unsatistfactory hack and I wished the root of the problem would be addressed by the Cypress team.

4reactions
MatthewWaanderscommented, Jan 3, 2022

Hi @momesana just sending this message to thank you, the combination of these commands fixed this issue for us as well. I’ll still be keeping this issue open for the Cypress team to keep it visible as an existing issue.

Read more comments on GitHub >

github_iconTop Results From Across the Web

DOMException on calling navigator.clipboard.readText()
Show activity on this post. Workaround, Just paste it in setTimeout, and then focus on document.
Read more >
Navigator Clipboard API DOMException Javascript Fix
If you are seeing Uncaught DOMException: Document is not focused when using navigator.clipboard.readText() or navigator.clipboard.
Read more >
JS error: "DOMException: Document is not focused"? - Reddit
I get this error in JavaScript when trying to read from the clipboard. I've read up on the concept of focus in JavaScript,...
Read more >
How to read from and write to the clipboard in JavaScript
Don't try the above code in the console. To use the Clipboard API, the document needs to be in a focused state. Otherwise,...
Read more >
Navigator Clipboard API - Medium
Chrome. Document is not focused. This error happens in Chrome when there is delay in writing to clipboard and user is not focusing...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found