Paste newlines into clipboard via Javascript - javascript

Before any asks, I did research this thoroughly and the answer has not been post here previously.
I want to send some plain text configuration text to the clipboard with Javascript. The text will consist of multiple commands, one command per line, so that the user may then past into a configuration file on his PC (call it "myconfig.ini") using a text editor (most commonly, Notepad.exe).
I tried the following:
var cCRLF = String.fromCharCode(10,13);
var cText = 'This is command line 1'+cCRLF;
cText += 'This is command line 2'+cCRLF;
cText += 'This is command line 3'+cCRLF;
cText += 'This is command line 4';
window.clipboardData.setData('Text', cText);
but when I execute and paste into notepad, I don't get individual lines and the line return character (cCRLF) is not viewable (that nasty little box character appears).
Does someone have a solution for this?

The solution is to use back-tick (` `)
alert(`string text line 1
string text line 2`);
For reference:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/template_strings

I would suggest using some other method than the clipboard for sending data to the user. This method only works in IE and can be disabled (and newer IE versions prompt first): Get clipboard data as array in javascript
A CSS popup box (which the user can copy from themselves) would probably be a nicer (and cross-platform) solution. This might help: http://www.pat-burt.com/web-development/how-to-do-a-css-popup-without-opening-a-new-window/

I think i did find a solution. It's a bit weird, but hey, it's for IE. It's a modified snippet I found on stackoverflow.
<body>
<a href="#" onclick='test("This\nIS\nA\nTEST")'>TEST</a>
<div id="cb" style="position: absolute; left: -2000px"></div>
</body>
<script>
function test(cText) {
cText= cText.replace(/\n\r?/g, "<br>");
// create an editable DIV and append the HTML content you want copied
var editableDiv = document.getElementById("cb");
with (editableDiv) {
contentEditable = true;
}
editableDiv.innerHTML= cText;
// select the editable content and copy it to the clipboard
var r = document.body.createTextRange();
r.moveToElementText(editableDiv);
r.select();
r.execCommand("Copy");
// deselect, so the browser doesn't leave the element visibly selected
r.moveToElementText(document.body);
r.select();
}
</script>

Related

Simulate paste into Textarea with javascript

When pasting data from the clipboard into an html textarea, it does some pretty cool parsing to make the paste look close to what was copied as far as newlines go.
For example, I have the following html on a page that I select (everything highlights in blue) and then I copy it:
Hello
<br>
<br>
<br>
<div>more</div>
<div>last</div>
So to be clear, what I am copying is what the output of this jsfiddle looks like.
Now when I paste this magical, copied text into a text area, I see exactly what I would expect: "Hello", empty line, empty line, empty line, "more", "last". Cool! Then when I use jQuery's .val() on the textarea, I get "Hello\n\n\nmore\nlast". Super cool. It took the br's and div's and was able to infer the correct newlines from it.
Now...
What I am trying to do it programmatically take the same data I copied earlier and set it as the textarea's value as if it were pasted.
Here is what I have tried...
So, say the stuff I copied earlier was wrapped in a <div id="parent">...</div>.
var parent = $("#parent");
var textarea = $("#theTextArea");
// Set the value of the text area to be the html of the thing I care about
textarea.val(parent.html());
Now I know this isn't the same as a copy-paste, but I was hoping it would take care of me and do what I wanted. It doesn't. The textarea gets filled with Hello<br><br><br><div>more</div><div>last</div>. The html that was once invisible is now stringified and made part of the text.
Obviously I did this wrong. .html() returns, of course, the string of html. But is there something I could call on parent that would give me the text with all inferred linebreaks?. I have tried calling parent.text(), but this only gives Hellomorelast (no line breaks).
A few notes that could help with an answer: I am using Angular, so I have access to all their goodies and jQuery.
Edit:
Solution
It is not nice but you can try to replace html tags with line breaks '\n' or do some line breaks in the html file and get the content with text().
var parent1 = $("#paren1");
var textarea1 = $("#theTextArea1");
var parent2 = $("#paren2");
var textarea2 = $("#theTextArea2");
// Set the value of the text area to be the html of the thing I care about
var text = parent1.html();
text = text.replace(new RegExp("<br>", 'g'),"\n");
text = text.replace(new RegExp("<div>", 'g'),"");
text = text.replace(new RegExp("</div>", 'g'),"\n");
textarea1.val(text);
textarea2.val(parent2.text());
JSFiddle

Indesign Server Scripting Textarea.Contents

I am creating a Javascript script to use with Indesign Server (CS3).
Trying to find all textareas within a document and find the contents of them.
I can easily loop through all the textareas, using the functions provided by Adobe.
However, when i try to get the content of the TextArea, I only get the content that is visible within that textarea, not the out port text.
document.TextAreas[0].contents
In other words, if the Indesign document contains a textarea with a little plus sign, indicating that there is more text, but it did not fit, then my script does not return the hidden text.
Or, to put it another words again. Can i get the entire content when the 'overflows' property of the 'textarea' is false;
Full code:
function FindAllTextBoxes(){
var alertMessage;
for (var myCounter = myDoc.textFrames.length-1; myCounter >= 0; myCounter--) {
var myTextFrame = myDoc.textFrames[myCounter];
alertMessage += "\nTextbox content: " + myTextFrame.contents;
alertMessage += "\nOverflow:" + myTextFrame.overflows;
alert(alertMessage);
}
}
How can I read the full content of the Textarea?
A little late, but just came across this. This is tested with InDesign CS5 - the following line will get all of the overflown text from a TextFrame:
var content = myTextFrame.parentStory.contents;
Hope this helps!

Need Solution on NicEdit Insert HTML text into Instance

i am using this function to insert text into NicEdit,
function insertAtCursor(editor, value){
var editor = nicEditors.findEditor(editor);
var range = editor.getRng();
var editorField = editor.selElm();
editorField.nodeValue = editorField.nodeValue.substring(0, range.startOffset) +
value +
editorField.nodeValue.substring(range.endOffset, editorField.nodeValue.length);}
This code works fine for simple text but when i pass HTML content into it, it does not render the HTML output in div instead it dumps the HTML code as it is into the Instance Div.
Example:
<div class="one">Some text here</div>
This must show in the Instance as "Some text here"
and remaining code hidden in source code.
Can any one give me a solution to fix this problem?
After working whole night and trying different solutions I had finally got it working! :)
In case any one wants to know solution for this, I had to add a Replace function
replace()
for the content and made it support HTML.
See my answer HERE. It's a plugin I created to insert html at the cursor position.

Display current line and column number for a textarea

I'm making a file edit interface in my web-app, I have a textarea with file contents.
When textarea is focused, I want to output the position of the cursor, i.e. line number and column: this is useful because error messages usually yield a line number, for example.
The question is: how do I figure out the position of the cursor in textarea?
I'm using prototype library. Maybe there's a solution already?
I'm not really interested in fancy toolbars for the textarea, which are offered by those advanced widgets.
When I want the current line number of textarea and current column of textarea, I solved like this:
<textarea onkeyup="getLineNumberAndColumnIndex(this);" onmouseup="this.onkeyup();" >
</textarea>
function getLineNumberAndColumnIndex(textarea){
var textLines = textarea.value.substr(0, textarea.selectionStart).split("\n");
var currentLineNumber = textLines.length;
var currentColumnIndex = textLines[textLines.length-1].length;
console.log("Current Line Number "+ currentLineNumber+" Current Column Index "+currentColumnIndex );
}
You may want to check out these 2 links:
http://www.dedestruct.com/2008/03/22/howto-cross-browser-cursor-position-in-textareas/[The orginal source does not exist any more, the modified link points to the latest version of the Web Archive]
https://developer.mozilla.org/En/DOM:Selection
..once you have a selection (cursor index in text), you can split your text by newlines, thus getting line number. you can get column by determining index from beginning of a line

Greasemonkey\JavaScript Copy to Clipboard button

I am trying to write a JavaScript script to add to greasemonkey that adds a button after an element. The onClick for this button should copy the parents element text to the keyboard. I have seen plenty of examples that copy already selected text to the clipboard such as this:
<SCRIPT LANGUAGE="JavaScript">
<!-- Begin
function copyit(theField) {
var selectedText = document.selection;
if (selectedText.type == 'Text') {
var newRange = selectedText.createRange();
theField.focus();
theField.value = newRange.text;
} else {
alert('Alert: Select The text in the textarea then click on this button');
}
}
// End -->
</script>
<input onclick="copyit(this.form.text_select)" type="button" value="Click Here to Copy the Highlighted Text" name="copy_button">
Found here.
I have also found that you can select text in input elements. I have tried combining both techniques, as well as many others with no viable solution yet. I am not even sure why the code above copies to the clipboard. Does anyone have a solution to this?
If you took the time to read the full article, the author states this doesn't work for Firefox...
Actually, I think it doesn't even work for IE, as it does nothing related to the clipboard!
There is a technique using Flash, because by default, Firefox inhibits clipboard access for security reasons.
Otherwise, the classical way to do copy is:
var tc = textToCopy.replace(/\n\n/g, '\n');
if (window.clipboardData) // IE
{
window.clipboardData.setData("Text", tc);
}
else
{
unsafeWindow.netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
const clipboardHelper = Components.classes
["#mozilla.org/widget/clipboardhelper;1"].
getService(Components.interfaces.nsIClipboardHelper);
clipboardHelper.copyString(tc);
}
after enabling copy (for a given site).
Are you sure your example works? It does not in my browser. But take a look at the following page: http://www.jeffothy.com/weblog/clipboard-copy/

Categories