Beginner here :)
I am getting the following error: Failed to make request: Cannot read properties of undefined (reading 'writeText')
I made a button in my embedded js file that would copy to clipboard a global variable (html table that was generated by js) in a GET request.
It doesn't work locally and even if that was the issue I tested it on the secure website (https) and it also didn't work.
Everything I can find is made for the DOM and as far as I understand I can't use that in a JS with express js file.
app.get("/copyToClipboard", async (req, res) => {
try {
console.log("inside copy to clip");
await navigator.clipboard.writeText(tableFull);
res.render("index.ejs");
} catch (error) {
console.error("Failed to make request:", error.message);
res.render("index.ejs", {
error: error.message,
});
}
// res.sendFile(__dirname + "/index.html");
});
I tried using a clipboard tool:
clipboardjs.com
It also uses DOM, so didn't work. In desperation, I tried sending it with a POST request, which didn't make sense to me, but I tried anyway.
I tried to find the npm install code for the Clipboard API, but I couldn't find any other packages than what I showed above. It seems like it can find navigator.clipboard, but the problem is arising with writeText
The error
Cannot read properties of undefined (reading 'writeText')basically meansCan't get the method writeText from the object it's called from, because the object is undefined. So the clipboard object isundefinedand in this case, also the navigator object.To understand the underlying problem better, at this point one should check the documentation of the navigator object. In the documentation we see, that
So on we go, checking the documentation of the window object, which tells us that
Which basically means, the
windowobject (thus also thenavigatorobject) are only available when working with the DOM, so only in.ejsor.htmlfiles. It does not exist in the context of the nodejs server.So to solve your problem, any code that wants to utilize the window object, must be inside a template. In your case this means
await navigator.clipboard.writeText(tableFull);needs to be moved inside a script tag inindex.ejs.Also I would not recommend implementing a route for only small procedures like copying something to the clipboard, rather try to implement them on the client side or use something like event emitters. And if you do have procedures on a route, do not redirect the user to that page, but use the fetchAPI (just as a general tip, maybe you are already doing so)
Hope this helps, feel free to ask for further help or clarifications :)