42

I write the path of a document into the alert box via using below code.

var oArg = new Object();
oArg.Document = $(t).attr("path") + str + "/" + $(t).attr("name");
alert(oArg.Document);

Assume that message is : "documents/files/img/stack.jpg"

I only want to copy this text with a button. For Chrome Ctrl + C is ok for it but for IE, Ctrl + C copies everything at the alertbox.

How can I copy only the message with using a button?

Ctrl + C works like below:

  • Chrome - Works perfectly.
  • Internet Explorer - Works, but you get extra text. The caption and OK button text is also copied, along with a bunch of dashes. This is almost never what you want.
  • Firefox - Doesn't work at all You must select the text before you can copy it.
1
  • I would prefer to use console.log :) Apr 10, 2018 at 5:58

3 Answers 3

87

What you can do is to prompt the user with the text and ask them to copy it. As such:

prompt("Copy to clipboard: Ctrl+C, Enter", oArg.Document);

Because if you supply a text to the prompt it automatically gets selected. Does this suit you?

3
  • 1
    Good solution, how can I close that prompt screen and the opener window with ok button in prompt screen?
    – Stack Over
    Jul 11, 2013 at 11:08
  • You listen for the return value of the prompt. if (prompt("Blah bla?")){ doStuff(); }
    – Eric
    Jun 26, 2014 at 21:44
  • 1
    nice trick thanks, wouldn't use it for production because it's terrible UI/UX, but works for me :D
    – Andrew
    Feb 19, 2016 at 19:32
20

When ever the alert message box appears with the text message , just press CTRL+ C and your message will be copied, then you can paste it anywhere you want , no need to write it or using any other method to get the text.

1
  • 10
    As mentioned in the questioner a simple ctrl+c doesn't works in all browsers.
    – bish
    Jul 10, 2015 at 10:29
15

I've found that, in Chrome at least, the alert box text is in fact selectable -- when the text does not contain any line-breaks (ie. "\n").

I don't know why this is the case, but I've had to use this trick before for quick selection prompts. (you could also use prompt("please press ctrl+c to copy the text below", "text to copy"), but that usually looks worse)

1
  • 1
    I noticed that if you have another function in the alert, (i.e. JSON.stringify(), btoa()), you can place the \n in there and text can then be selected.
    – shmuels
    Nov 1, 2018 at 14:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.