DOMException on calling navigator.clipboard.readText() - javascript

Following lines of code used to work and stopped working after chrome upgrade to Version 74.0.3729.169 (Official Build) (64-bit). Now I get DOMException even though permission is set correctly. Appreciate if you can explain what is the bug and workaround. Exception details:
message:Document is not focused
name:NotAllowedError
code:0
navigator.permissions.query({ name: 'clipboard-read' }).then(result => {
// If permission to read the clipboard is granted or if the user will
// be prompted to allow it, we proceed.
if (result.state === 'granted' || result.state === 'prompt') {
navigator.clipboard.readText()
.then(text => {
//my code to handle paste
})
.catch(err => {
console.error('Failed to read clipboard contents: ', err);
});
}
}

This seems to happen when executing code from the devtools console or snippets.
Workaround:
You can execute the code below and focus on the window within 3 seconds, by clicking somewhere, or just by pressing <tab>.
e.g. from snippets
Ctrl-Enter
<Tab>
e.g. from console
Enter
<Tab>
setTimeout(async()=>console.log(
await window.navigator.clipboard.readText()), 3000)

The issue I was having was that I had an alert to say that the text had been copied, and that was removing focus from the document. Ironically, this caused the text to not be copied. The workaround was quite simple:
clipboard.writeText(clippy_button.href).then(function(x) {
alert("Link copied to clipboard: " + clippy_button.href);
});
Just show the alert when the Promise is resolved. This might not fix everybody's issue but if you came here based on searching for the error this might be the correct fix for your code.

As Kaiido said, your DOM need to be focused. I had the same problem during my development when i put a breakpoint in the code... The console developper took the focused and the error appear. With the same code and same browser, all work fine if F12 is closed

Problem
It's a security risk, clearly. :)
Solution
I assume you face this when you are trying to call it from the dev tools. Well, to make life easier, I am taking Jannis's answer, to a less adrenaline-oriented way. :)
I am adding a one-time focus listener to window to do the things magically after hitting "tab" from the Devtools.
function readClipboardFromDevTools() {
return new Promise((resolve, reject) => {
const _asyncCopyFn = (async () => {
try {
const value = await navigator.clipboard.readText();
console.log(`${value} is read!`);
resolve(value);
} catch (e) {
reject(e);
}
window.removeEventListener("focus", _asyncCopyFn);
});
window.addEventListener("focus", _asyncCopyFn);
console.log("Hit <Tab> to give focus back to document (or we will face a DOMException);");
});
}
// To call:
readClipboardFromDevTools().then((r) => console.log("Returned value: ", r));
Note: The return value is a Promise as it's an asynchronous call.

if you want to debug a and play around to view result. also can hide this <p></p>.
async function readClipboard () {
if (!navigator.clipboard) {
// Clipboard API not available
return
}
try {
const text = await navigator.clipboard.readText();
document.querySelector('.clipboard-content').innerText = text;
} catch (err) {
console.error('Failed to copy!', err)
}
}
function updateClipboard() {
// Here You Can Debug without DomException
debugger
const clipboard = document.querySelector('.clipboard-content').innerText;
document.querySelector('.clipboard-content').innerText = 'Updated => ' + clipboard;
}
<button onclick="readClipboard()">Paste</button>
<p class="clipboard-content"></p>
<button onclick="updateClipboard()">Edit</button>

As the exception message says, you need to have the Document actively focused in order to use this API.

Suppose there is a p element. you want to copy its innerText.
So, lets not use navigation.clipboard (because 0f the error your are facing)
So below given is a example which copies the innerText of the p element when that button is clicked. your do not to rely upon "clicking" the button manually by using the code below. you can trigger the "click" by executing code like pElement.click() from devtools console.
Your devtools console problem, that #jannis-ioannou mentioned in his post above, will not occur!
function myFunction() {
var copyText = document.getElementById("copy-my-contents");
var range = document.createRange();
var selection = window.getSelection();
range.selectNodeContents(copyText);
selection.removeAllRanges();
selection.addRange(range);
document.execCommand("copy");
}
<p id="copy-my-contents">copy-me</p>
<button onclick="myFunction()">Copy text</button>

I was facing this in a Cypress test, this fixed it for me:
first focus the copy icon/button which is about to be clicked, then
use cy.realClick from cypress-real-events instead of cy.click

I just discovered that I don't need to write any code to debug this. When you pause on a breakpoint in Chrome DevTools, it adds a small yellow box to the page you're debugging which says, "Paused in debugger" and has play and step over buttons. I've never used it before, preferring the more extensive controls in DevTools.
I just discovered that if you use the step over button in this yellow box, the DOM stays focused and no error is thrown.

Cypress - Use the right window/navigator and focus on the document.
I tried to programatically populate the clipboard in my Cypress test so I could paste the contents into a text-area input element.
When I was struggling with this issue I found out that there were two things causing the problem.
The first issue was that I used the wrong window. Inside the test function scope window returns the Window object in test scope, while cy.window() returns the Window object for the Application Under Test (AUT).
Second issue was that document was not in focus, which can be easily resolved by calling cy.window().focus();.
Since both result in the same DOMException:
NotAllowedError: Document is not focused.
It was not always clear that there were 2 issues going on. So when debugging this:
Make sure you use the right window/navigator of the page you are testing.
Make sure that the document is focused on.
See following Cypress tests demonstrating the above:
describe('Clipboard tests', () => {
before(() => {
cy.visit('/');
// Focus on the document
cy.window().focus();
});
it('window object in test scope is not the window of the AUT', () => {
cy.window().then((win) => {
expect(window === win).to.equal(false);
expect(window.navigator === win.navigator).to.equal(false);
})
});
it('See here the different results from the different Window objects', () => {
expect(window.navigator.clipboard.writeText('test').catch(
(exception) => {
expect(exception.name).to.equal('NotAllowedError')
expect(exception.message).to.equal('Document is not focused.')
},
));
cy.window().then((win) => {
return win.navigator.clipboard.writeText('test').then(() => {
return win.navigator.clipboard.readText().then(
result => expect(result).to.equal('test'),
);
});
});
})
});

We saw a handful of these in our production app, and after some digging it turned out that the root cause in our case was the user was copying a lot of data, and switched tabs during the process (thus causing the relevant DOM to lose focus, and triggering the error). We were only able to replicate this by using CPU throttling in chrome, and even then it doesn't happen every time!
There was nothing to be "fixed" in this case - instead we're just catching the error and notifying the user via a toast that the copy failed and that they should try again. Posting in case it's of use to anyone else seeing this!

If you're using Selenium and getting this, you need to bring the test window to the front:
webDriver.switchTo().window(webDriver.getWindowHandle());
I have to do this repeatedly so I have it in a loop with a Thread.sleep() until the the paste works.
Full details: https://stackoverflow.com/a/65248258/145976

Related

How to integrate Quill-comment with React-quill?

I currently have this Code SandBox where I am trying to get React-Quill and Quill-Comment to work together so that I can let users comment on content that has been written.
Quill comment is not a react package and I am a react noob so I don't know if what I am trying to do it even possible. It appears to partially work because the toolbar add comment button registers the click event.
let commentCallback;
function commentAddClick(callback) {
setOpen(true); //show the modal
commentCallback = callback; //Appears to do nothing?
console.log("callback :>> ", callback); //Nothing is ever in the callback
console.log("commentAddClick");
}
However, the callback value doesn't appear to have or do anything. When I click the add comment button in the modal:
const commentSave = () => {
const comment = "This is a comment, forced for testing";
commentCallback(comment);
console.log("comment :>> ", comment);
//let comment = $('#commentInput').val();
commentCallback(comment);
addCommentToList(comment, currentTimestamp);
};
it throws an error that tells me
commentCallback is not a function
I am attempting to following the Vanilla JS example see line 68 here. I assume this problem is related to this warning message that spams on every keypress.
quill:toolbar ignoring attaching to nonexistent format comments-add
<button type="button" class="ql-comments-add"></button>
How do I resolve the warning message, and get the callback to work? Or, secondarily, is there another good commenting library that will work with Quill?
A working example in Vanilla JS can be found here:
https://github.com/nhaouari/quill-comment/tree/master/example/quill-comment-test
I'd like to replicate this in React.
The library you are referring to says that callback function will be null when nothing is selected in the editor. So, you need to select some text in the editor for the callback function to work.

Why doesn't "console.log()" work on this website?

I can open the Chrome DevTools console for this URL: https://www.google.com/ and enter the following command to print "Hello world!" to the console:
console.log("Hello world!")
However, when I attempt to use the same command for this URL: https://svc.mt.gov/dor/property/prc my message isn't printed in the console. Why is that?
Is there any way to force the console to work for this MT website?
I've tried using python/selenium to open the page and execute_script() to issue the command, but that hasn't worked either.
If you do
console.dir(console.log)
and click on the [[FunctionLocation]], you'll see the following in the site's source code:
"Debug" != e && (window.console.log = function() {}
)
Seems like a cheap (but lazy?) way to suppress logging on production.
One way to fix it, kinda, would be to use one of the many other console commands. (console.dir, or console.error, if you want)
If you really want the original console.log to work again, the only way to do that would be to run code before the page code runs, so that you can save a reference to the function. For example, with a userscript:
// <metadata block...>
// #grant none
// ==/UserScript==
const origConsoleLog = console.log;
// set original window.console.log back to its original
// after the page loads
setTimeout(() => {
window.console.log = origConsoleLog;
}, 2000);
// there are more elegant but more complicated approaches too
CertainPerformance already explained how this is possible and what the reason for suppressing the log seems to be. I'm going to show here another method to get back console.log after the original has been lost.
document.body.appendChild(document.createElement('IFRAME')).onload = function () {
this.contentWindow.console.log('Hello, World!');
this.remove();
};
This basically uses an old method of restoring global objects from a temporary iframe.

testcafe: Check for something after every click

I am testing a web app that renders some of its errors as HTML and gives no other indication that a problem occurred. After every click, I would like to see if a .error element exists.
I know I could manually add this after every click, but it's going to obfuscate my test and it will be easy to forget some instances. Is there a way to tell testcafe that a certain condition should make the test fail, even if I'm not explicitly checking for it?
I did something like this:
const scriptContent = `
window.addEventListener('click', function () {
if($('.error').length > 0) {
throw new Error($('.error').text());
}
});
`;
fixture`Main test`
.page`../../dist/index.html`.clientScripts(
{ content: scriptContent }
);
This injects a script onto the page I am testing. After every click, it uses jQuery to see if an error class exists. If it does, it throws an error on the page I'm testing. Testcafe reports the message of that error.
I'm hoping there's a better way.

Taking element screenshots in a loop. Detecting and skipping hidden web elements. Using puppeteer

I am taking screenshots of 'strip' elements on a webpage. Im having trouble detecting elements that are not currently displayed on the site.
I am taking screenshots of all the desktop elements on a website.
What I have tried is using await page.$$eval('section .strip', p => p.map((e) => e.getAttribute('display')))
Im also aware that I could use getcomputedstyles() but dont understand where to add this with regards to map().
let arr = await await page.$$('section .strip');
let naming = await page.$$eval('section .strip', p => p.map((e) => e.previousElementSibling.getAttribute('id')))
for(el in arr){
await arr[el].screenshot({path: './' +naming[el] + '.png'})
}
I expect a screenshot to be taken if the element is there and ignored if the element is visible (display: hidden).
What i am getting is, When using element.screenshot() Im getting and error of (node:3736) UnhandledPromiseRejectionWarning: Error: Node is either not visible or not an HTMLElement
No, it does not simply ignore the element if the element does not exist. It throws an error as you are experiencing.
Solution
As the code (see link about) is already checking if the element has a bounding box, you do not need to check this yourself. Instead, you can ignore the error by wrapping the expression in a try..catch like this:
for(el in arr){
try {
await arr[el].screenshot({path: './' +naming[el] + '.png'})
} catch (err) {
console.log(`No screenshot for ${naming[el]}: ${err.message}`);
}
}
This will try to take screenshot of all elements and log the elements for which this was not possible.

Cannot toggle fullscreen in testcafe

I have a react page in an iframe with a button that can enter fullscreen mode. I've tested this manually with firefox and chrome which both work. However, clicking with testcafe does not go to fullscreen mode and fails the test.
I'm assuming the iframe isn't the issue because it works manually but wanted to mention it just in case.
This is some of the app:
fs.fullScreen = function () {
const el = (fsEl && fsEl.current) || document.documentElement
if (el.requestFullscreen) return el.requestFullscreen()
if (el.mozRequestFullScreen) return el.mozRequestFullScreen()
if (el.webkitRequestFullscreen) return el.webkitRequestFullscreen()
if (el.msRequestFullscreen) return el.msRequestFullscreen()
}
<button onClick={fs.fullScreen}>Fullscreen</button>
This is the test that fails:
beforeEach((t) => t.switchToIframe(storybook.iframe))
afterEach((t) => t.switchToMainWindow())
test('The Fullscreen button enters fullscreen mode', async (t) => {
const { description, fullscreenButton } = storybook.hooks.fullscreen
await t
.expect(description.textContent)
.contains('Browser not in fullscreen mode')
.click(fullscreenButton)
.expect(description.textContent)
.contains('Browser in fullscreen mode')
})
In Firefox I've seen the console error: Request for fullscreen was denied because Element.requestFullscreen() was not called from inside a short running user-generated event handler.
In Chrome, I've seen the console error: Uncaught TypeError: fullscreen error.
The firefox error is fairly clear but I don't know how to work around it with testcafe. There is a way by editing the firefox profile before running the test but that won't work for chrome or other browsers. Is the chrome issue likely to be for the same reason?
This seems like it would be a common issue that automation frameworks have solved, so I might be missing something obvious?
I was able to reproduce the issue in the simple example:
Test page:
<button id="btn">click me</button>
<script>
var button = document.getElementById('btn');
button.addEventListener('click', function () {
button.requestFullscreen();
});
</script>
Test code
test(`test`, async t => {
await t.click('#btn');
});
I'm not sure whether this functionality will be supported or not, since we need to research it in detail.
As a workaround, you can mock the requestFullscreen method on the target element. It will suppress the error, but won't bring your page to the fullscreen layout. Check the following code as a reference:
const mockFullcreen = ClientFunction(element => element.requestFullscreen = () => {});
await mockFullcreen(target);
await t.click(target);

Categories

Resources