how to catch error for navigator.clipboard.writeText - javascript

navigator.clipboard.writeText
doesn't work on all browsers. I tried the following code. it works and copies on firefox but on opera, it shows the alert that the code is copied but actually, it doesn't copy the link and doesn't show the error prompt. and on the browser console, it shows this error: Uncaught (in promise) DOMException: Document is not focused.
so, how can I catch this error to show the link in prompt for the user to copy it manually?
if not possible, what is the most supported way to copy the current link to the clipboard?
let shareProjectBtn = document.getElementById("share-project-btn");
function copyCurrentURL() {
navigator.clipboard.writeText(window.location.href);
try {
if (navigator.clipboard.value !== null) {
alert("Project's link copied to clipboard");
}
} catch (error) {
window.prompt("Your browser can't copy the link, please copy this link manually",window.location.href);
}
}

You could use Promise.catch() to handle it. Here's an example grabbed straight from MDN:
navigator.clipboard.writeText("<empty clipboard>").then(() => {
/* clipboard successfully set */
}, () => {
/* clipboard write failed */
});

navigator.clipboard.writeText returns a Promise, so you can either:
move it into your try block and use:
await navigator.clipboard.writeText(window.location.href)
or use:
navigator.clipboard.writeText(window.location.href).catch((err) => window.prompt("Your browser can’t copy the link, …"))
You can read more about Promises here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

Related

Copy and paste localStorage data to clipboard on click

So let's say i have data in localStorage and there's 25 different names. How do i copy and paste that localStorage data via clipboard by clicking buttons.
This is the code of button that needs to copy localStorage data:
<div id="Shape1"><div id="Shape1_text"><span style="color:#303C49;font-family:Arial;font-size:16px;"><strong>Скопировать данные</strong></span></div></div>
I tried to copy using js code, but somehow it only run if i run that through console:
function copyjson() {
copy(JSON.stringify(localStorage));
}
You need something like this:
async function copyContent() {
try {
await navigator.clipboard.writeText(
JSON.stringify(localStorage)
);
console.log('Content copied to clipboard');
/* Resolved - text copied to clipboard successfully */
} catch (err) {
console.error('Failed to copy: ', err);
/* Rejected - text failed to copy to the clipboard */
}
}
The copy function is only used for debugging on console, and isn't actually a function that you can use in scripts (you will see that if you try to access it via window.copy).
Take a look at the Clipboard API and specifically to the .write method.

How to throw a javascript error during runtime via browser (Chrome)?

My objective: Test out my error handling functionality.
Temporary solution: Have a custom route: /error, which contains code which purposefully produces fatal error.
var a = undefined;
a.b.c // Breaks.
The above works, but I can't use it to test production site as the page is not required.
I was looking for a way to test it via the browser. I tried simply adding"
throw new Error("Custom error thrown here") to the console. That doesn't actually break it during runtime.
I tried adding a break point and adding the same code: throw new Error("Custom error thrown here"). That didn't work either.
Any other easier ways to do this rather than the above?
I was looking for a way where I can do it via browser only.
Thanks.
You did not clearly mention how and where the error should be thrown. I will assume that you can use a modified copy of your JavaScript file to throw errors. The modified file will reside on your computer and only be used when you're using Chrome developer tools. This feature is called Local Overrides. The steps are as follows:
Open the webpage
Open Chrome developer tools for that webpage
In Sources panel go to Overrides tab
Click Select folder for overrides and choose a folder on your computer
A warning appears on the webpage which reads "DevTools requests full access to ..." which you must allow
In Sources panel go to Page tab
Locate the file in which you need to inject the "throw error" code
Right click and choose Save for overrides
Now you can edit the copy of the file on your computer or from within developer tools. Insert the code that produces the error at the desired location. When you reload the page with developer tools open, Chrome will load the local copy of the JavaScript file and throw the error. The error thrown that way will contain the context from where it originated e.g. call stack. If the developer tools are closed then live copy will be used.
If I got your question right, this is How you can do it from the console:
var script_tag = document.createElement('script');
script_tag.type = 'text/javascript';
script_tag.text = 'throw new Error("Custom error thrown here")';
document.body.appendChild(script_tag);
Or if you want you can trigger it on click:
var script_tag = document.createElement('script');
script_tag.type = 'text/javascript';
script_tag.text = 'window.document.onclick = function() { throw new Error("Custom error thrown here")}';
document.body.appendChild(script_tag);
And then you click anywhere on the page, to throw the error;
I would use the exec function which actually takes string and runs the code within at compile time.
exec('a.b.c')
You won't be able to throw an error inside your application from the console, since you are out of scope of the app.
Having said that, one slightly awkward way you could do this is by adding a breakpoint at the start of the javascript file.
Reload the page and your app will pause at the breakpoint - you can then modify the code as you need - like adding a throw new Error("something...") - and save your edits.
Then allow the code to run and you will see your error.
A downside is if you reload the changes will be gone, but I believe it's as close as you can get to modifying code at runtime.
Add this code to your production code
window.addEventListener('err', () => {
throw new Error('break it');
})
and when you want to create an error simply
dispatchEvent(new Event('err'))
in the console
You can use a global variable, which is accessible from your app and from debug console.
if (window.shouldThrow) {
throw new Error("Custom error thrown here");
}
This way you can turn on/off the exception throwing using the window.shouldThrow variable.
Try this way to catch error detail on run time
try
{
var a = undefined;
a.b.c // Breaks.
}
catch ( e )
{
alert("Error: " + e.description );
}

What is the equivalent command to close for chrome.runtime.openOptionsPage?

In a Chrome extension what is the equivalent of close to chrome.runtime.openOptionsPage? I have tried:
window.close();
and
chrome.runtime.closeOptionsPage();
This would need to be invoked from within the options page itself.
Update
According to wOxxOm in the comments below, "window.close()" should work. So this may be a bug in my browser Edge.
wOxxOm suggested using "chrome.tabs.remove". However I get an error using it this way from within the options script:
chrome.tabs.getCurrent(function(tab) {
chrome.tabs.remove(tab.id, function() { });
});
Error handling response: TypeError: Cannot read property 'id' of undefined

Listen(capture) an iframe console logs

I'm trying to catch console logs of an iframe which I don't have access to its source and its implementation.
<iframe src="an http address" name="my-iframe" allowFullScreen/>
When the iframe logs data I see them in my console. But the problem is,
this piece of code
// define a new console
var console = (function(oldCons){
return {
log: function(text){
oldCons.log(text);
if(text === "hi"){
alert("text")
}
},
info: function (text) {
oldCons.info(text);
if(text === "hi"){
alert("text")
}
},
warn: function (text) {
oldCons.warn(text);
if(text === "hi"){
alert("text")
}
},
error: function (text) {
oldCons.error(text);
if(text === "hi"){
alert("text")
}
}
};
}(window.console));
//Then redefine the old console
window.console = console;
Which I got from this post is not working for the iframe logs. It only works on my app console logs.
If the src is a different domain, and you can't run code directly on the other domain (for example, by being able to modify or insert a .js into it), then there's nothing you can do. This is for security reasons: browsers don't want to leak any information between domains unless the sender of the information deliberately allows it.
If you can alter code on the other domain, you could monkeypatch the console and have it pass the log information to the parent window with postMessage so that the parent can do something with it.
If you happen to be trying to examine messages for your personal use only (rather than for use by random people on the internet), you can modify your browser to run your custom JavaScript on the other domain with a userscript, by using a userscript manager like Tampermonkey.

Programmatically access webpage error details in browsers

Is there some way to access webpage warning/error details using JavaScript?
For instance, errors in IE show up in the bottom left corner like so:
I would like to able to access the details of this error (in IE as well as other browsers if possible) using JavaScript.
Any suggestions?
EDIT: I'm not looking for debuggers. I want to access the content of the error details/error console. Alternately, figuring out how to create a global exception handler equivalent for JavaScript would help too
You may want to use the window.onerror event. You can consider this event as a sort of global exception handler. The value returned by onerror determines whether the browser displays a standard error message. If you return false, the browser displays the standard error message in the JavaScript console. If you return true, the browser does not display the standard error message. (Source)
<script type="text/javascript">
window.onerror=function(msg, url, line){
alert('An error has occurred' + msg);
return true;
}
</script>
<script type="text/javascript">
// Syntax error
document.write('hi there'
</script>
You can also use traditional exception handling in JavaScript to catch run-time errors.
try
{
document.write(junkVariable)
}
catch (exception)
{
document.write(exception)
}
The output of the above would be:
‘junkVariable’ is undefined
EDIT: As noted by psychotik's comment, the window.onerror event does not work in Google Chrome. (Source)

Categories

Resources