Copy and paste localStorage data to clipboard on click - javascript

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.

Related

how to catch error for navigator.clipboard.writeText

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

How to save input data form with javascript avoid security content policy -Chrome extension

i'm newbie on developping chrome extension and i'm facing a problem.
I need to get user input data and store it in some ways. I tryed with local.storage and sync.storage but they should work only with same domain since i cannot get data while i'm trying to inject javascript by using script in content.js file. It works on same domain (i suppose that in this case, when i open tab of chrome extension, local.storage save data only for that "domain").
How can solve it?
Thank you
You can try the message passing.
// popup.js
function submit(data) {
chrome.tabs.query({active: true}, function (tabs) {
chrome.tabs.sendMessage(tabs[0].id, data);
});
}
// content.js
chrome.runtime.onMessage.addListener(function (message) {
// do sth
});

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.

Paste document files in javascript

I'd like to paste file to server from client desktop using javascript.
So I added a listener on paste event:
document.addEventListener('paste', function(e) {
var files = {};
if(window.clipboardData){ // IE
files = window.clipboardData.files;
}
else {
files = e.clipboardData.files;
}
//...some functions using files
});
Event fires correctly but the problem is - e.clipboardData.files has always length of 0. I'm using ctrl+c on my desktop's .docx file. Am I missing something? My browsers are Firefox Quantum 57 and Google Chrome 60 on Ubuntu 16.04.
It is useful for users to be able to use clipboard keyboard shortcuts such as ctrl+c and ctrl+v. Chromium exposes read-only files on the clipboard as outlined below. This triggers when the user hits the operating system's default paste shortcut or when the user clicks Edit and then Paste in the browser's menu bar. No further plumbing code is needed.
document.addEventListener("paste", async e => {
e.preventDefault();
if (!e.clipboardData.files.length) {
return;
}
const file = e.clipboardData.files[0];
// Read the file's contents, assuming it's a text file.
// There is no way to write back to it.
console.log(await file.text());
});

How to get Chrome Extension's Options value in Extension? [duplicate]

I have an options page where the user can define certain options and it saves it in localStorage: options.html
Now, I also have a content script that needs to get the options that were defined in the options.html page, but when I try to access localStorage from the content script, it doesn't return the value from the options page.
How do I make my content script get values from localStorage, from the options page or even the background page?
Update 2016:
Google Chrome released the storage API: https://developer.chrome.com/docs/extensions/reference/storage/
It is pretty easy to use like the other Chrome APIs and you can use it from any page context within Chrome.
// Save it using the Chrome extension storage API.
chrome.storage.sync.set({'foo': 'hello', 'bar': 'hi'}, function() {
console.log('Settings saved');
});
// Read it using the storage API
chrome.storage.sync.get(['foo', 'bar'], function(items) {
message('Settings retrieved', items);
});
To use it, make sure you define it in the manifest:
"permissions": [
"storage"
],
There are methods to "remove", "clear", "getBytesInUse", and an event listener to listen for changed storage "onChanged"
Using native localStorage (old reply from 2011)
Content scripts run in the context of webpages, not extension pages. Therefore, if you're accessing localStorage from your contentscript, it will be the storage from that webpage, not the extension page storage.
Now, to let your content script to read your extension storage (where you set them from your options page), you need to use extension message passing.
The first thing you do is tell your content script to send a request to your extension to fetch some data, and that data can be your extension localStorage:
contentscript.js
chrome.runtime.sendMessage({method: "getStatus"}, function(response) {
console.log(response.status);
});
background.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.method == "getStatus")
sendResponse({status: localStorage['status']});
else
sendResponse({}); // snub them.
});
You can do an API around that to get generic localStorage data to your content script, or perhaps, get the whole localStorage array.
I hope that helped solve your problem.
To be fancy and generic ...
contentscript.js
chrome.runtime.sendMessage({method: "getLocalStorage", key: "status"}, function(response) {
console.log(response.data);
});
background.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.method == "getLocalStorage")
sendResponse({data: localStorage[request.key]});
else
sendResponse({}); // snub them.
});
Sometimes it may be better to use chrome.storage API. It's better then localStorage because you can:
store information from your content script without the need for
message passing between content script and extension;
store your data as JavaScript objects without serializing them to JSON (localStorage only stores strings).
Here's a simple code demonstrating the use of chrome.storage. Content script gets the url of visited page and timestamp and stores it, popup.js gets it from storage area.
content_script.js
(function () {
var visited = window.location.href;
var time = +new Date();
chrome.storage.sync.set({'visitedPages':{pageUrl:visited,time:time}}, function () {
console.log("Just visited",visited)
});
})();
popup.js
(function () {
chrome.storage.onChanged.addListener(function (changes,areaName) {
console.log("New item in storage",changes.visitedPages.newValue);
})
})();
"Changes" here is an object that contains old and new value for a given key. "AreaName" argument refers to name of storage area, either 'local', 'sync' or 'managed'.
Remember to declare storage permission in manifest.json.
manifest.json
...
"permissions": [
"storage"
],
...
Another option would be to use the chromestorage API. This allows storage of user data with optional syncing across sessions.
One downside is that it is asynchronous.
https://developer.chrome.com/extensions/storage.html
[For manifest v3]
You can execute a script that returns localstorage items from the webpage. This script can be executed from popup or background service worker.
Add this line in manifest.json:
"permissions": ["scripting"]
let [tab] = await chrome.tabs.query({ active: true, currentWindow: true })
// Execute script in the current tab
const fromPageLocalStore = await chrome.scripting.executeScript({
target: { tabId: tabId },
func: () => {
return JSON.stringify(localStorage)
}
})
const localStorageItems = JSON.parse(fromPageLocalStore[0].result)

Categories

Resources