Copying Image Data to Clipboard?
I am working on a site where the client has a coupon code image on a product page and when the user cl开发者_运维知识库icks on the image he wants that code copied to the clipboard... is this possible?
With JavaScript clipboard access is pretty much disabled in all browsers unless a user enables it in their settings. The work around is using a Flash Copy to clipboard script, but Flash is getting more security restrictions set on that. Check out zeroclipboard.
If you want the image to be copied, you can use "createControlRange()" like so:
var imageTag = document.getElementById("couponCode");
if (document.body.createControlRange) //to check if browser is IE
{
var couponRange;
document.getElementById("couponCode").contentEditable = true;
couponRange = document.body.createControlRange();
couponRange.addElement(imageTag);
couponRange.execCommand('Copy');
document.getElementById("couponCode").contentEditable = false;
alert("Image copied");
}
else //for other browsers
{
alert("Your browser does not allow access to clipboard.\nPlease press Ctrl+C to copy");
var couponRange = document.createRange();
couponRange.selectNode(imageTag);
window.getSelection().removeAllRanges();
window.getSelection().addRange(couponRange);
}
Browsers other than IE do not allow Javascript to access the clipboard for security reasons. But you can invoke the browser functionality by asking the user to press Ctrl+C after selecting the range of the coupon image.
Hope this solves your problem.
精彩评论