Last active
August 13, 2020 09:48
-
-
Save jsuryahyd/dbde3357ccec2ece8ff60eb992899347 to your computer and use it in GitHub Desktop.
Clipboard reading with browser js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
- https://developer.mozilla.org/en-US/docs/Web/API/Clipboard/read | |
- https://stackoverflow.com/a/23024504/7314900 | |
- https://stackoverflow.com/a/54132144/7314900 | |
*/ | |
function getTextFromBlob(blob){ | |
var reader = new FileReader(); | |
reader.onload = function() { | |
console.log(reader.result); | |
} | |
return reader.readAsText(blob); | |
//another way | |
// const text1 = await new Response(blob).text() | |
} | |
function getClipboardData(){ | |
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.read().then(data => { | |
console.log(data); | |
for (let i=0; i<data.length; i++) { | |
if (data[i].type != "image/png") { | |
data[i].getType("text/plain").then(b=>getTextFromBlob(b)).catch(e=>console.error(e)) | |
} else { | |
const blob = data[i].getType("image/png"); | |
imgElem.src = URL.createObjectURL(blob); | |
} | |
} | |
}); | |
} | |
}); | |
} | |
getClipboardData(); | |
//if running from console, error will be thrown saying document is not focused, | |
//set timeout and focus the browser page, while the function runs in background |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment