I'd like to invoke a mailto link from JavaScript - that is I'd like a method that allows me to open the email client on the users PC, exactly as if they had clicked on a normal mailto link.
How can I do this?
You can use window.location.href here, like this:
window.location.href = "mailto:address#dmail.com";
You can avoid the blank page issue discussed above by instead using .click() with a link on the page:
document.getElementById('mymailto').click();
...
the working answer for me, tested in chrome, IE and firefox together with outlook was this
window.location.href = 'mailto:address#dmail.com?subject=Hello there&body=This is the body';
%0d%0a is the new line symbol of the email body in a mailto link
%20 is the space symbol that should be used, but it worked for me as well with normal space
Better to use
window.open('mailto:address#mail.com?subject=sub&body=this is body')
If we use window.location.href chrome browser is having error in network tab with Provisional headers are shown
Upgrade-Insecure-Requests: 1
Actually, there is a possibillity to avoid the empty page.
I found out, you can simply insert an iframe with the mailto link into the dom.
This works on current Firefox/Chrome and IE (also IE will display a short confirm dialog).
Using jQuery, I got this:
var initMailtoButton = function()
{
var iframe = $('<iframe id="mailtoFrame" src="mailto:name#domain.com" width="1" height="1" border="0" frameborder="0"></iframe>');
var button = $('#mailtoMessageSend');
if (button.length > 0) {
button.click(function(){
// create the iframe
$('body').append(iframe);
//remove the iframe, we don't need it any more
window.setTimeout(function(){
iframe.remove();
}, 500);
});
}
}
This is an old question, but I combined several Stack Overflows to come up with this function:
//this.MailTo is an array of Email addresses
//this.MailSubject is a free text (unsafe) Subject text input
//this.MailBody is a free text (unsafe) Body input (textarea)
//SpawnMail will URL encode /n, ", and ', append an anchor element with the mailto, and click it to spawn the mail in the users default mail program
SpawnMail: function(){
$("#MyMailTo").remove();
var MailList="";
for(i in this.MailTo)
MailList+=this.MailTo[i]+";";
var NewSubject=this.MailSubject.replace(/\n/g, "%0d%0a");
NewSubject=NewSubject.replace(/"/g, "%22");
NewSubject=NewSubject.replace(/'/g, "%27");
var NewBody=this.MailBody.replace(/\n/g, "%0d%0a");
NewBody=NewBody.replace(/"/g, "%22");
NewBody=NewBody.replace(/'/g, "%27");
$("#mainNavBar").after("<a id='MyMailTo' style='display:none;' href='mailto:"+MailList+"?subject="+NewSubject+"&body="+NewBody+"'> </a>");
document.getElementById('MyMailTo').click();
}
The cool part about this (and how I plan to use it) is I can put this in a loop and split out individual messages to everyone in the array or keep everyone together (which is what this function currently does).
Anyway thanks for the tip #Toskan
FOLLOW-UP - Please note the new HTML5 standard does not allow looping mailto (or other pop-up related js) without a "required user gesture". Cool article here: https://github.com/WICG/interventions/issues/12
So you can't use this to mass generate individual e-mails, but it does work well with sending to many in it's current design.
Related
Is it possible to call a javascript function from the URL? I am basically trying to leverage JS methods in a page I don't have access to the source.
Something like: http://www.example.com/mypage.aspx?javascript:printHelloWorld()
I know if you put javascript:alert("Hello World"); into the address bar it will work.
I suspect the answer to this is no but, just wondered if there was a way to do it.
There isn't from a hyperlink, no. Not unless the page has script inside specifically for this and it's checking for some parameter....but for your question, no, there's no built-in support in browsers for this.
There are however bookmarklets you can bookmark to quickly run JavaScript functions from your address bar; not sure if that meets your needs, but it's as close as it gets.
You can use Data URIs.
For example:
data:text/html,<script>alert('hi');</script>
For more information visit: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
Write in address bar
javascript:alert("hi");
Make sure you write in the beginning: javascript:
/test.html#alert('heello')
test.html
<button onClick="eval(document.location.hash.substring(1))">do it</button>
you may also place the followinng
<a href='javascript:alert("hello world!");'>Click me</a>
to your html-code, and when you click on 'Click me' hyperlink, javascript will appear in url-bar and Alert dialog will show
About the window.location.hash property:
Return the anchor part of a URL.
Example 1:
//Assume that the current URL is
var URL = "http://www.example.com/test.htm#part2";
var x = window.location.hash;
//The result of x will be:
x = "#part2"
Exmaple 2:
$(function(){
setTimeout(function(){
var id = document.location.hash;
$(id).click().blur();
}, 200);
})
Example 3:
var hash = "#search" || window.location.hash;
window.location.hash = hash;
switch(hash){
case "#search":
selectPanel("pnlSearch");
break;
case "#advsearch":
case "#admin":
}
Using Eddy's answer worked very well as I had kind of the same problem.
Just call your url with the parameters : "www.mypage.html#myAnchor"
Then, in mypage.html :
$(document).ready(function(){
var hash = window.location.hash;
if(hash.length > 0){
// your action with the hash
}
});
you can use like this situation:
for example, you have a page: http://www.example.com/page.php
then in that page.php, insert this code:
if (!empty($_GET['doaction']) && $_GET['doaction'] == blabla ){
echo '<script>alert("hello");</script>';
}
then, whenever you visit this url: http://www.example.com/page.php?doaction=blabla
then the alert will be automatically called.
Just use:
(function() {
var a = document.createElement("script");
a.type = "text/javascript";
a.src = "http://www.example.com/helloworld.js?" + Math.random();
document.getElementsByTagName("head")[0].appendChild(a)
})();
This basically creates a new JavaScript line in the head of the HTML to load the JavaScript URL you wish on the page itself. This seems more like what you were asking for. You can also change the a.src to the actual code, but for longer functions and stuff it becomes a problem. The source link can also link to a JavaScript file on your computer if targeted that way.
No; because it would make links extremely dangerous.
you can execute javascript from url via events
Ex: www.something.com/home/save?id=12<body onload="alert(1)"></body>
does work if params in url are there.
There is a Chrome extension called Bookmarklet URL (no affiliation). To append a URL with JavaScript, so that the JavaScript command is executed just after loading the webpage, one can use ?bmlet=javascript:
Example: Display an alert box
https://github.com/?bmlet=javascript:alert("Hi");
Example: Enable spell-checking while editing a GitHub README file
[Obviously, a spelling checking extension must be originally available.]
https://github.com/<username>/<repositoryname>/edit/main/README.md?bmlet=javascript:document.getElementById("code-editor").setAttribute("spellcheck","true");
On some pages, it might take some time, as the JavaScript command runs after completely loading the page. Simple commands like alert("Hi"); should run quickly.
I am a student and I have just realized my school blocked JavaScript from the address bar. It works with the "a" tag on a .html file but not on the bar anymore. I am not asking for help, I would just like to share this.
You can do one thing that is you can first open the link www.example.com. Then you can search:
javascript:window.alert("Hello World!")
I am trying do some modification to an greasemonkey userscript to implement a feature I need. The code is like
showAddress:function(addrString,type)
{
this.addrBox=$('<div id="batchPublish"></div>')
.append('<div id="batchHeader"></div>')
.append('<div id="batchContent" style="float:left;clear:both"></div>');
.........
var batchContent=this.addrBox.find('#batchContent')
.append('<pre width="300" style="text-align:left" id="batchedlink"></pre>');
this.addrBox.find('#batchedlink').css({'width':'500px','height':'250px','overflow':'auto','word-wrap': 'break-word'})
.append(addrString);
$.blockUI({message:this.addrBox,css:{width:"520px",height:"300px"}}); }
Basically this code writes data to html. What I want to implement is to have "addrString" written to an iframe embedded. Now It's in the "pre" tag. I have tried many approaches but still no luck. Iframe was always empty.
I am completely a novice in javascript and unclear whether this is possible.
Thank you for the help.
Since you are adding the iFrame in the same domain, then you can manipulate its contents like this:
(See it in action at jsBin.)
$("#batchContent").append ('<iframe id="batchedlink"></iframe>');
/*--- Compensate for a bug in IE and FF, Dynamically added iFrame needs
some time to become "DOM-able".
*/
setTimeout ( function () {
var iframeBody = $("#batchedlink").contents ().find ("body");
iframeBody.append (addrString);
},
333
);
NOTE:
For a Chrome userscript, you apparently don't need the timer delay. But for FF and IE 8 (the other 2 browsers I double-checked), a dynamically added iFrame is not manipulable until after it has "settled" for some reason. This seems to take about 200 mS.
A statically loaded iFrame does not have this lag, see the jsBin demo.
Sort of hard to tell exactly what you're asking -- but if you want to know whether or not you can append DOM elements to an iFrame, the answer is "no".
I am developing a WYSIWYG editor using the iframe technique. I need to know an idea to set a JavaScript method to overide keyboard event replacing charCode to another CharCode of a different language. For example if I am pressing "a" it will return the Arabic character set in Arabic language keyboard.
UPDATE - 14th May 2011
I have managed to implement a solution as suggested by #Tim only on chrome browser. I have noticed incompatibility of switching the designMode="on" when it is created inside the DOM using javascript. Following is the code and you can also see the test page here - jsfiddle
JAVASCRIPT - JQUERY
$(document).ready(function(){
var textarea = $("#textarea");
var frame = $("<iframe class='thaana-editor-html' id='editable' />");
$(frame).width('500px');
$(frame).height('250px'); $(textarea).parent().prepend(frame);
var iframe = document.getElementById("editable");
var iframeObject = $(iframe).contents().get(0);
iframeObject.designMode = "on";
});
HTML
<div id="content">
<textarea class="thaanaEditor" id="textarea" ></textarea>
</div>
I have tested on
Chrome v11 - works fine
IE8 - works fine
IE9 - not tested yet
Firefox -3.6 & 4 - NOT working - iframe is not editable as in designmode
I've answered a similar question before: Need to set cursor position to the end of a contentEditable div, issue with selection and range objects (see also Changing the keypress). The same technique applies to an editable iframe: you'll need to add the keypress event handler to the iframe's document. For example:
function handleKeypress(evt) {
// See linked answer for implementation
}
var iframe = document.getElementById("your_iframe_id");
var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
if (iframeDoc.addEventListener) {
iframeDoc.addEventListener("keypress", handleKeypress, false);
} else if (iframeDoc.attachEvent) {
iframeDoc.attachEvent("onkeypress", handleKeypress);
}
As I understand you want to force your user to write with your virtual keyboard, for example when user pressed D you display ي and ...
In Persian we mostly use this javascript library created by Mahdi HashemiNezhad. With this your user can change between Persian & English keyboard. To change the keyboard for your locale, you can replace the Unicode equivalents (for arabic users most of it are in the right place and some ofthem are changed)
let meknow if there is a problem
Is it possible to call a javascript function from the URL? I am basically trying to leverage JS methods in a page I don't have access to the source.
Something like: http://www.example.com/mypage.aspx?javascript:printHelloWorld()
I know if you put javascript:alert("Hello World"); into the address bar it will work.
I suspect the answer to this is no but, just wondered if there was a way to do it.
There isn't from a hyperlink, no. Not unless the page has script inside specifically for this and it's checking for some parameter....but for your question, no, there's no built-in support in browsers for this.
There are however bookmarklets you can bookmark to quickly run JavaScript functions from your address bar; not sure if that meets your needs, but it's as close as it gets.
You can use Data URIs.
For example:
data:text/html,<script>alert('hi');</script>
For more information visit: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
Write in address bar
javascript:alert("hi");
Make sure you write in the beginning: javascript:
/test.html#alert('heello')
test.html
<button onClick="eval(document.location.hash.substring(1))">do it</button>
you may also place the followinng
<a href='javascript:alert("hello world!");'>Click me</a>
to your html-code, and when you click on 'Click me' hyperlink, javascript will appear in url-bar and Alert dialog will show
About the window.location.hash property:
Return the anchor part of a URL.
Example 1:
//Assume that the current URL is
var URL = "http://www.example.com/test.htm#part2";
var x = window.location.hash;
//The result of x will be:
x = "#part2"
Exmaple 2:
$(function(){
setTimeout(function(){
var id = document.location.hash;
$(id).click().blur();
}, 200);
})
Example 3:
var hash = "#search" || window.location.hash;
window.location.hash = hash;
switch(hash){
case "#search":
selectPanel("pnlSearch");
break;
case "#advsearch":
case "#admin":
}
Using Eddy's answer worked very well as I had kind of the same problem.
Just call your url with the parameters : "www.mypage.html#myAnchor"
Then, in mypage.html :
$(document).ready(function(){
var hash = window.location.hash;
if(hash.length > 0){
// your action with the hash
}
});
you can use like this situation:
for example, you have a page: http://www.example.com/page.php
then in that page.php, insert this code:
if (!empty($_GET['doaction']) && $_GET['doaction'] == blabla ){
echo '<script>alert("hello");</script>';
}
then, whenever you visit this url: http://www.example.com/page.php?doaction=blabla
then the alert will be automatically called.
Just use:
(function() {
var a = document.createElement("script");
a.type = "text/javascript";
a.src = "http://www.example.com/helloworld.js?" + Math.random();
document.getElementsByTagName("head")[0].appendChild(a)
})();
This basically creates a new JavaScript line in the head of the HTML to load the JavaScript URL you wish on the page itself. This seems more like what you were asking for. You can also change the a.src to the actual code, but for longer functions and stuff it becomes a problem. The source link can also link to a JavaScript file on your computer if targeted that way.
No; because it would make links extremely dangerous.
you can execute javascript from url via events
Ex: www.something.com/home/save?id=12<body onload="alert(1)"></body>
does work if params in url are there.
There is a Chrome extension called Bookmarklet URL (no affiliation). To append a URL with JavaScript, so that the JavaScript command is executed just after loading the webpage, one can use ?bmlet=javascript:
Example: Display an alert box
https://github.com/?bmlet=javascript:alert("Hi");
Example: Enable spell-checking while editing a GitHub README file
[Obviously, a spelling checking extension must be originally available.]
https://github.com/<username>/<repositoryname>/edit/main/README.md?bmlet=javascript:document.getElementById("code-editor").setAttribute("spellcheck","true");
On some pages, it might take some time, as the JavaScript command runs after completely loading the page. Simple commands like alert("Hi"); should run quickly.
I am a student and I have just realized my school blocked JavaScript from the address bar. It works with the "a" tag on a .html file but not on the bar anymore. I am not asking for help, I would just like to share this.
You can do one thing that is you can first open the link www.example.com. Then you can search:
javascript:window.alert("Hello World!")
In Internet Explorer I can use the clipboardData object to access the clipboard. How can I do that in FireFox, Safari and/or Chrome?
For security reasons, Firefox doesn't allow you to place text on the clipboard. However, there is a workaround available using Flash.
function copyIntoClipboard(text) {
var flashId = 'flashId-HKxmj5';
/* Replace this with your clipboard.swf location */
var clipboardSWF = 'http://appengine.bravo9.com/copy-into-clipboard/clipboard.swf';
if(!document.getElementById(flashId)) {
var div = document.createElement('div');
div.id = flashId;
document.body.appendChild(div);
}
document.getElementById(flashId).innerHTML = '';
var content = '<embed src="' +
clipboardSWF +
'" FlashVars="clipboard=' + encodeURIComponent(text) +
'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
document.getElementById(flashId).innerHTML = content;
}
The only disadvantage is that this requires Flash to be enabled.
The source is currently dead: http://bravo9.com/journal/copying-text-into-the-clipboard-with-javascript-in-firefox-safari-ie-opera-292559a2-cc6c-4ebf-9724-d23e8bc5ad8a/ (and so is its Google cache)
There is now a way to easily do this in most modern browsers using
document.execCommand('copy');
This will copy currently selected text. You can select a textArea or input field using
document.getElementById('myText').select();
To invisibly copy text you can quickly generate a textArea, modify the text in the box, select it, copy it, and then delete the textArea. In most cases this textArea wont even flash onto the screen.
For security reasons, browsers will only allow you copy if a user takes some kind of action (ie. clicking a button). One way to do this would be to add an onClick event to a html button that calls a method which copies the text.
A full example:
function copier(){
document.getElementById('myText').select();
document.execCommand('copy');
}
<button onclick="copier()">Copy</button>
<textarea id="myText">Copy me PLEASE!!!</textarea>
Online spreadsheet applications hook Ctrl + C and Ctrl + V events and transfer focus to a hidden TextArea control and either set its contents to desired new clipboard contents for copy or read its contents after the event had finished for paste.
See also Is it possible to read the clipboard in Firefox, Safari and Chrome using JavaScript?.
It is summer 2015, and with so much turmoil surrounding Flash, here is how to avoid its use altogether.
clipboard.js is a nice utility that allows copying of text or html data to the clipboard. It's very easy to use, just include the .js and use something like this:
<button id='markup-copy'>Copy Button</button>
<script>
document.getElementById('markup-copy').addEventListener('click', function() {
clipboard.copy({
'text/plain': 'Markup text. Paste me into a rich text editor.',
'text/html': '<i>here</i> is some <b>rich text</b>'
}).then(
function(){console.log('success'); },
function(err){console.log('failure', err);
});
});
</script>
clipboard.js is also on GitHub.
As of 2017, you can do this:
function copyStringToClipboard (string) {
function handler (event){
event.clipboardData.setData('text/plain', string);
event.preventDefault();
document.removeEventListener('copy', handler, true);
}
document.addEventListener('copy', handler, true);
document.execCommand('copy');
}
And now to copy copyStringToClipboard('Hello, World!')
If you noticed the setData line, and wondered if you can set different data types, the answer is yes.
Firefox does allow you to store data in the clipboard, but due to security implications it is disabled by default. See how to enable it in "Granting JavaScript access to the clipboard" in the Mozilla Firefox knowledge base.
The solution offered by amdfan is the best if you are having a lot of users and configuring their browser isn't an option. Though you could test if the clipboard is available and provide a link for changing the settings, if the users are tech savvy. The JavaScript editor TinyMCE follows this approach.
The copyIntoClipboard() function works for Flash 9, but it appears to be broken by the release of Flash player 10. Here's a solution that does work with the new flash player:
http://bowser.macminicolo.net/~jhuckaby/zeroclipboard/
It's a complex solution, but it does work.
I have to say that none of these solutions really work. I have tried the clipboard solution from the accepted answer, and it does not work with Flash Player 10. I have also tried ZeroClipboard, and I was very happy with it for awhile.
I'm currently using it on my own site (http://www.blogtrog.com), but I've been noticing weird bugs with it. The way ZeroClipboard works is that it puts an invisible flash object over the top of an element on your page. I've found that if my element moves (like when the user resizes the window and i have things right aligned), the ZeroClipboard flash object gets out of whack and is no longer covering the object. I suspect it's probably still sitting where it was originally. They have code that's supposed to stop that, or restick it to the element, but it doesn't seem to work well.
So... in the next version of BlogTrog, I guess I'll follow suit with all the other code highlighters I've seen out in the wild and remove my Copy to Clipboard button. :-(
(I noticed that dp.syntaxhiglighter's Copy to Clipboard is broken now also.)
Check this link:
Granting JavaScript access to the clipboard
Like everybody said, for security reasons, it is by default disabled. The page above shows the instructions of how to enable it (by editing about:config in Firefox or the user.js file).
Fortunately, there is a plugin called "AllowClipboardHelper" which makes things easier with only a few clicks. however you still need to instruct your website's visitors on how to enable the access in Firefox.
Use the modern document.execCommand("copy") and jQuery. See this Stack Overflow answer.
var ClipboardHelper = { // As Object
copyElement: function ($element)
{
this.copyText($element.text())
},
copyText:function(text) // Linebreaks with \n
{
var $tempInput = $("<textarea>");
$("body").append($tempInput);
$tempInput.val(text).select();
document.execCommand("copy");
$tempInput.remove();
}
};
How to call it:
ClipboardHelper.copyText('Hello\nWorld');
ClipboardHelper.copyElement($('body h1').first());
// jQuery document
;(function ( $, window, document, undefined ) {
var ClipboardHelper = {
copyElement: function ($element)
{
this.copyText($element.text())
},
copyText:function(text) // Linebreaks with \n
{
var $tempInput = $("<textarea>");
$("body").append($tempInput);
//todo prepare Text: remove double whitespaces, trim
$tempInput.val(text).select();
document.execCommand("copy");
$tempInput.remove();
}
};
$(document).ready(function()
{
var $body = $('body');
$body.on('click', '*[data-copy-text-to-clipboard]', function(event)
{
var $btn = $(this);
var text = $btn.attr('data-copy-text-to-clipboard');
ClipboardHelper.copyText(text);
});
$body.on('click', '.js-copy-element-to-clipboard', function(event)
{
ClipboardHelper.copyElement($(this));
});
});
})( jQuery, window, document );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span data-copy-text-to-clipboard=
"Hello
World">
Copy Text
</span>
<br><br>
<span class="js-copy-element-to-clipboard">
Hello
World
Element
</span>
I've used GitHub's Clippy for my needs and is a simple Flash-based button. It works just fine if one doesn't need styling and is pleased with inserting what to paste on the server-side beforehand.
http://www.rodsdot.com/ee/cross_browser_clipboard_copy_with_pop_over_message.asp works with Flash 10 and all Flash enabled browsers.
Also ZeroClipboard has been updated to avoid the bug mentioned about page scrolling causing the Flash movie to no longer be in the correct place.
Since that method "Requires" the user to click a button to copy this is a convenience to the user and nothing nefarious is occurring.
A slight improvement on the Flash solution is to detect for Flash 10 using swfobject:
http://code.google.com/p/swfobject/
And then if it shows as Flash 10, try loading a Shockwave object using JavaScript. Shockwave can read/write to the clipboard (in all versions) as well using the copyToClipboard() command in Lingo.
Try creating a memory global variable storing the selection. Then the other function can access the variable and do a paste. For example,
var memory = ''; // Outside the functions but within the script tag.
function moz_stringCopy(DOMEle, firstPos, secondPos) {
var copiedString = DOMEle.value.slice(firstPos, secondPos);
memory = copiedString;
}
function moz_stringPaste(DOMEle, newpos) {
DOMEle.value = DOMEle.value.slice(0, newpos) + memory + DOMEle.value.slice(newpos);
}
If you support Flash, you can use https://everyplay.com/assets/clipboard.swf and use the flashvars text to set the text.
https://everyplay.com/assets/clipboard.swf?text=It%20Works
That’s the one I use to copy and you can set as extra if it doesn't support these options. You can use:
For Internet Explorer:
window.clipboardData.setData(DataFormat, Text) and window.clipboardData.getData(DataFormat)
You can use the DataFormat's Text and URL to getData and setData.
And to delete data:
You can use the DataFormat's File, HTML, Image, Text and URL. PS: You need to use window.clipboardData.clearData(DataFormat);.
And for other that’s not support window.clipboardData and swf Flash files you can also use Control + C button on your keyboard for Windows and for Mac its Command + C.
From addon code:
For how to do it from Chrome code, you can use the nsIClipboardHelper interface as described here: https://developer.mozilla.org/en-US/docs/Using_the_Clipboard
Use document.execCommand('copy'). It is supported in the latest versions of Chrome, Firefox, Edge, and Safari.
function copyText(text){
function selectElementText(element) {
if (document.selection) {
var range = document.body.createTextRange();
range.moveToElementText(element);
range.select();
} else if (window.getSelection) {
var range = document.createRange();
range.selectNode(element);
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
}
}
var element = document.createElement('DIV');
element.textContent = text;
document.body.appendChild(element);
selectElementText(element);
document.execCommand('copy');
element.remove();
}
var txt = document.getElementById('txt');
var btn = document.getElementById('btn');
btn.addEventListener('click', function(){
copyText(txt.value);
})
<input id="txt" value="Hello World!" />
<button id="btn">Copy To Clipboard</button>
Clipboard API is designed to supersede document.execCommand. Safari is still working on support, so you should provide a fallback until the specification settles and Safari finishes implementation.
const permalink = document.querySelector('[rel="bookmark"]');
const output = document.querySelector('output');
permalink.onclick = evt => {
evt.preventDefault();
window.navigator.clipboard.writeText(
permalink.href
).then(() => {
output.textContent = 'Copied';
}, () => {
output.textContent = 'Not copied';
});
};
Permalink
<output></output>
For security reasons clipboard Permissions may be necessary to read and write from the clipboard. If the snippet doesn't work on Stack Overflow give it a shot on localhost or an otherwise trusted domain.
Building off the excellent answer from David from Studio.201, this works in Safari, Firefox, and Chrome. It also ensures no flashing could occur from the textarea by placing it off-screen.
// ================================================================================
// ClipboardClass
// ================================================================================
var ClipboardClass = (function() {
function copyText(text) {
// Create temp element off-screen to hold text.
var tempElem = $('<textarea style="position: absolute; top: -8888px; left: -8888px">');
$("body").append(tempElem);
tempElem.val(text).select();
document.execCommand("copy");
tempElem.remove();
}
// ============================================================================
// Class API
// ============================================================================
return {
copyText: copyText
};
})();