I'm trying to write in javascript and I want to understand why it doesn't work?
sample order code that I want to copy: 593004485164756431
when I copy to clipboard : 593004485164756500
I checked for an error in the console, there was no error, does the browser affect the error? i use firefox
this my code
function copyToClipboard(text) {
if (navigator.clipboard && window.isSecureContext) {
return navigator.clipboard.writeText(text)
} else {
// text area method
let textArea = document.createElement("textarea")
textArea.value = text
// make the textarea out of viewport
textArea.style.position = "fixed"
textArea.style.left = "-999999px"
textArea.style.top = "-999999px"
document.body.appendChild(textArea)
textArea.focus()
textArea.select()
return new Promise((res, rej) => {
// here the magic happens
document.execCommand('copy') ? res() : rej()
textArea.remove()
})
}
}
on button
<img onclick="copyToClipboard({{ $result['code_order'] }})" style="width:20px;cursor:pointer;" src="{{ url('img/copy-solid.svg') }}"/>
I hope I can find the solution to this problem. Thank you
Related
I want to paste image from my clipboard to whatsapp chat from clipboard i tried using document exec command with different parameters like insertHTML , insertImage these two add image in content editable div but does not enable the send button. I also tried using document exec command paste but its pasting nothing. I double checked and images exists on clipboard.
async function sendToChat(blob) {
setToClipboardImg(blob)
try {
document.querySelector('._6h3Ps ._13NKt').focus()
} catch (e) {
document.querySelector('textarea').focus()
}
// const data = [new ClipboardItem({
// [text.type]: text
// })]
// await navigator.clipboard.write(data)
document.execCommand("Paste", null, null);
//setToClipboardWithTextInsta()
}
var setToClipboardImg = async blob => {
window.focus();
const data = [new ClipboardItem({
[blob.type]: blob
})]
await navigator.clipboard.write(data);
}
I needed exactly the same funcionality, I was able to resolve it using html2canvas, you can convert an html element into an image and then send it through whatsapp from the clipboard, here is how I implemented it:
document.querySelector("#btn").onclick(function () {
var table = document.querySelector("#table");
var elementContainer = document.querySelector("#previewImage");
try {
// Prevent duplicates since the element will be appended to the container
if (elementContainer.innerHTML) {
elementContainer.innerHTML = "";
}
html2canvas(table).then(canvas => {
elementContainer.appendChild(canvas);
canvas.toBlob(blob => navigator.clipboard.write([new
ClipboardItem({'image/png': blob})]));
alert('😁 The screenshot for the table currently displayed was copied to the clipboard, you can now paste into the WhatsApp chats 😁');
});
}
catch(err){
document.querySelector("#output").innerHTML = err.message;
}
}
Then in the head of the document add the following cdn:
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
I have a form input in my vue app that is used to create a password. I've successfully added a button to show/hide the password. I want to add a copy to clipboard function to let the user copy and paste the password in a safe place, but it's not working. What am I doing wrong here?
Template code
<small class="font-wieght-bold text-success mb-0" v-if="isCopied">Copied</small>
<div class="input-group">
<input :type="showPassword ? 'text' : 'password'" class="form-control" ref="password" required v-model="password">
<div class="input-group-append">
<button class="btn btn-secondary" #click.prevent="copyToClipboard()"><i class="fas fa-clipboard"></i></button>
</div>
</div>
Vue code
viewPassword() {
this.showPassword = !this.showPassword;
},
copyToClipboard() {
this.$refs.password.select();
document.execCommand('copy');
this.isCopied = true;
setTimeout( () => { this.isCopied = !this.isCopied },3000);
}
You need to copy the contents of your v-model, not the input itself.
You can use a function like this to copy from a variable.
It makes a new text box, uses the copy command, then immediately removes it. All in a single event loop so it never even renders.
const copyTextToClipboard = (text) => {
const textArea = document.createElement('textarea')
//
// *** This styling is an extra step which is likely not required. ***
//
// Why is it here? To ensure:
// 1. the element is able to have focus and selection.
// 2. if element was to flash render it has minimal visual impact.
// 3. less flakyness with selection and copying which **might** occur if
// the textarea element is not visible.
//
// The likelihood is the element won't even render, not even a flash,
// so some of these are just precautions. However in IE the element
// is visible whilst the popup box asking the user for permission for
// the web page to copy to the clipboard.
//
// Place in top-left corner of screen regardless of scroll position.
textArea.style.position = 'fixed'
textArea.style.top = '0'
textArea.style.left = '0'
// Ensure it has a small width and height. Setting to 1px / 1em
// doesn't work as this gives a negative w/h on some browsers.
textArea.style.width = '2em'
textArea.style.height = '2em'
// We don't need padding, reducing the size if it does flash render.
textArea.style.padding = 0
// Clean up any borders.
textArea.style.border = 'none'
textArea.style.outline = 'none'
textArea.style.boxShadow = 'none'
// Avoid flash of white box if rendered for any reason.
textArea.style.background = 'transparent'
textArea.value = text
document.body.appendChild(textArea)
textArea.select()
try {
const successful = document.execCommand('copy')
const msg = successful ? 'successful' : 'unsuccessful'
console.log('Copying text command was ' + msg)
} catch (err) {
console.log('Oops, unable to copy')
}
document.body.removeChild(textArea)
}
As an alternative solution to the one of the accepted answer I've tried with the clipboard API. In particular I've used the clipboard.writeText() method to copy the v-modeled data directly into the clipboard and it worked also with <input type="password">
Here is the refactored code of copyToClipboard() method:
copyToClipboard() {
navigator.clipboard.writeText(this.password);
this.isCopied = true;
setTimeout( () => { this.isCopied = !this.isCopied },3000);
}
I have the following Page
When I click "Click Here To Copy", it calls document.execCommand("copy") to copy some text to the clipboard and it works.
However, when I hit the button "Open popup", it opens a div in the same page (no iframe), then when clicking on "Click Here To Copy", document.execCommand("copy") doesn't work.
Steps to reproduce :
document.execCommand("copy") works :
However if I open the popup, document.execCommand("copy") doesn't work
Does anyone know the reason for that please ?
Thanks
cheers,
Here is my entire code :
function CopyToClipBoard(d){
var c=document.createElement("textarea");
c.innerText=d;
document.body.appendChild(c);
c.select();
document.execCommand("copy");
document.body.removeChild(c);
}
<div onclick="CopyToClipBoard('text to be copied')">Click Here To copy</div>
Here is the cause of the problem :
The following code doesn't seem to work when there is an overlay of a document. For example when the caller is on a div with higher z-index or something... I'm not sure on what exactly causes this code to fail. But it seems related to overlayers, focusable elements or something... The fact is that, when the body of the document is hidden, the created text area is unable to focus and it doesn't work.
function CopyToClipBoard(d){
var c=document.createElement("textarea");
c.innerText=d;
document.body.appendChild(c);
c.select();
document.execCommand("copy");
document.body.removeChild(c);
}
<div onclick="CopyToClipBoard('text to be copied')">Click Here To copy</div>
Solution :
Instead of adding the text area to the body of the document, it can be added to the caller itself... Hence it will always be in the foreground. This assumes the text to copy is short such that the execution is fast enough for the user not to notice the creation and the removal of the text area...
function CopyToClipBoard(item, d){
var c=document.createElement("textarea");
c.value=d;
c.style.maxWidth = '0px';
c.style.maxHeight = '0px';
item.appendChild(c);
c.focus();
c.select();
document.execCommand("copy");
item.removeChild(c);
}
<div onclick="CopyToClipBoard(this,'text to be copied')">Click Here To copy</div>
Here is my working example of copyTextToClipboard function. Please try to add textArea.focus call.
const fallbackCopyTextToClipboard = text => {
const textArea = document.createElement('textarea');
textArea.value = text;
textArea.style.position = 'fixed';
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
document.execCommand('copy');
document.body.removeChild(textArea);
}
const copyTextToClipboard = text => {
if (navigator.clipboard) {
return navigator.clipboard.writeText(text);
}
return new Promise((resolve, reject) => {
fallbackCopyTextToClipboard(text);
resolve();
});
};
I'm playing about with PDF.js, and can't seem to find a solution to my problem.
I have a PDF with a trim area and bleed, I need to get the trim area so that I can crop the PDF image data in HTML canvas.
I see that Acrobat has javascript that can return the Trim based on getPageBox("Trim"). Is there any equivalent in PDF.js?
I cant seem to find a reference when inspecting the Javascript PDF Object in the console.
I was able to get it after editing pdf.worker.js. Tested with 1.7.225. First, Add get trimBox() after get cropBox() like this:
get trimBox() {
var trimBox = this.getInheritedPageProp('TrimBox', true);
if (!isArray(trimBox) || trimBox.length !== 4) {
return shadow(this, 'trimBox', this.mediaBox);
}
return shadow(this, 'trimBox', trimBox);
},
Now, in handler.on('GetPage', function ... of WorkerMessageHandler, add a few lines like this:
handler.on('GetPage', function wphSetupGetPage(data) {
return pdfManager.getPage(data.pageIndex).then(function (page) {
var rotatePromise = pdfManager.ensure(page, 'rotate');
var refPromise = pdfManager.ensure(page, 'ref');
var userUnitPromise = pdfManager.ensure(page, 'userUnit');
var viewPromise = pdfManager.ensure(page, 'view');
var trimBoxPromise = pdfManager.ensure(page, 'trimBox'); //added
return Promise.all([
rotatePromise,
refPromise,
userUnitPromise,
viewPromise,
trimBoxPromise //added
]).then(function (results) {
return {
rotate: results[0],
ref: results[1],
userUnit: results[2],
view: results[3],
trimBox: results[4] //added
That's it. Now you can get the trim box in your app by page.pageInfo.trimBox.
In addition to the excellent answer from #Sangbok Lee,
If you use the latest PDF.js version, the this.getInheritedPageProp function has changed to
this._getInheritableProperty('TrimBox', true)
Figured it out.
For anyone else who may be interested in pdf.worker.js on line 2654 I added the following that exposed the trimBox.
tboxX = this.pageDict.map.TrimBox[0];
tboxY = this.pageDict.map.TrimBox[1];
tboxW = this.pageDict.map.TrimBox[2];
tboxH = this.pageDict.map.TrimBox[3];
I'm sure there is a neater way, but it works.
I decided to try a different approach to this problem. Instead of relying on a string I thought it would be more efficient for this specific issue to use the function location.path to determine the source of the album-cover. Here's what I only have so far:
The piece of HTML for the image:
<img src="http://static.last.fm/flatness/catalogue/noimage/noalbum_g3.png" width="220" height="220" class="album-cover"/>
The piece of Javascript I have:
var albumCover = document.getElementsByClassName('album-cover') // Get the album cover
var currentLink = location.pathname
var dictionary =
{ // location.pathname : image source for albumCover
'/music/King+Crimson/Red' : 'http://i1325.photobucket.com/albums/u622/last_fm_projeKct/Last%20FM%20covers/Red.jpg',
'/music/King+Crimson/Discipline' : 'http://i1325.photobucket.com/albums/u622/last_fm_projeKct/Last%20FM%20covers/Discipline.jpg'
}
Now here's the piece of the code that's incomplete:
if (currentLink === ''// first part of the dictionary)
{
albumCover.src = '' second part of the dictionary
};
else{};
Any help is welcome and thanks for reading, cheers.
Old Post:
a follow-up on a question I asked recently but I can't seem to be able to change the code to match what I'm looking for. The code occurs on the following website: link
I'm interested in changing the image source in the code below. However, the new image source is to be determined based on what the H1-element of that webpage contains.
<div class="g3 album-cover-wrapper album-cover-wrapper--no-cover " >
<img src="http://static.last.fm/flatness/catalogue/noimage/noalbum_g3.png" width="220" height="220" class="album-cover"/>
<section class="r add-top-margin remove-bottom-margin">
<div class="g4"> </div>
</section>
</div>
Now I thought it would be useful to use 'dictionary-list' like following:
if H1 contains the string 'Discipline'{img.src="newsource.jpg'};
Thanks for taking the time to read this, cheers!
Edit: here's a piece of code I tried but I'm guessing it needs more info for it to actually work.
var headerDef = document.getElementsByTagName('h1'),
var img = document.getElementsByClassName('album-cover');
if (headerDef === 'Red')
{
img.src = "newsource.jpg";
};
else{};
A few examples of how the list will be:
//string in H1 : new image source for the 'album-cover'-class image
'Discipline' : 'http://ecx.images-amazon.com/images/I/41kcnkbxS-L._SL500_AA300_.jpg',
'Red' : 'http://img.noiset.com/images/album/king-crimson-red-4-cd-cover-31985.gif',
etc...
It's a list for which I'd have to manually add each instance of a page having a specific H1-string.
I'd suggest the following:
var map = {
'red': 'oh my gods!',
'blue': 'blue? Really..?'
};
function influenceImage(source, map) {
if (!source || !map) {
return false;
}
else {
var text = source.textContent || source.innerText;
for (var word in map) {
if (map.hasOwnProperty(word) && text.indexOf(word) !== -1) {
return map[word];
}
}
}
}
// in real life, with an image use:
// imageNode.src = influenceImage(document.getElementsByTagName('h1')[0], map);
document.getElementById('test').title = influenceImage(document.getElementsByTagName('h1')[0], map);
JS Fiddle demo.
In the demo I set the title attribute of an a element, but, of course, as noted in the comment simply set the src attribute of an image node.
The above changed, slightly (within the else {...}, to make it a case-insensitive search/match:
var text = (source.textContent || source.innerText).toLowerCase();
for (var word in map) {
if (map.hasOwnProperty(word) && text.indexOf(word.toLowerCase()) !== -1) {
return map[word];
}
}
JS Fiddle demo.
And another edit, again within the else {...}, in order to add a default option in case there's no word-match:
var text = (source.textContent || source.innerText).toLowerCase();
for (var word in map) {
if (map.hasOwnProperty(word) && text.indexOf(word.toLowerCase()) !== -1) {
return map[word];
}
}
// we only get here if the `for` loop and the `if` doesn't throw out a match.
return 'default string';
JS Fiddle demo.