I am designing an chrome extension for Gmail. In this I want to get selected/highlighted text. I tried following code:
if (!window.x) {
x = {};
}
x.Selector = {};
x.Selector.getSelected = function() {
var t = '';
if($('.compose-container').getSelection){
t = $('.compose-container').getSelection();
alert(t);
} else if (window.getSelection) {
t = window.getSelection();
} else if (document.getSelection) {
t = document.getSelection();
} else if (document.selection) {
t = document.selection.createRange().text;
}
return t;
}
It is not giving me selected text in compose mail.
Please help me out.
You would need to use the copy command to achieve this.
var copyText = document.execCommand('copy');
Basically it will copy any text selection in the browser.
You can check out this link on how it was fully utilized
As per gRenzFries answer, I code same as link provided by him. But slight addition in code to paste it in textbox.
Code to Copy text :
var emailLink = document.querySelector('.gmail_default');
var range = document.createRange();
range.selectNode(emailLink);
window.getSelection().addRange(range);
try {
// Now that we've selected the anchor text, execute the copy command
var successful = document.execCommand('copy', true);
} catch(err) {
}
Code to paste it in textbox:
$('#text-to-display').val(""); //reset textbox value
$('#text-to-display').focus(); //set focus to textbox
document.execCommand("Paste");
This code works just as expected.
Related
I'm building a chrome extension where selected text can have different highlighting styles applied to it. I used ranges to get this all to work, and I clone the range, put a span around it, and then delete the range and replace it with the cloned one. Everything seems fine except I've somehow managed to disable right clicking by triggering this behavior through the extension. I've narrowed it down the single line of range.surroundContents(span), but here's the full code section:
// Determines the selected text
document.onmouseup = function() {
var selection = document.getSelection();
selection = getSelectedText(color);
};
// Finds the text selected in the page, spans it, and gives it a class
function getSelectedText(inputColor) {
var span = document.createElement('span');
span.setAttribute('class', inputColor);
if(document.getSelection) {
var selection = document.getSelection();
if(selection.rangeCount == true) {
var range = selection.getRangeAt(0).cloneRange();
range.surroundContents(span);
selection.removeAllRanges();
selection.addRange(range);
}
}
}
Is there a way I can counter this? I've already tried using document.oncontextmenu = false directly following the problem line, but that's not bringing back right click. I also tried replacing it with newNode.appendChild(range.extractContents()); range.insertNode(newNode) as recommended by https://developer.mozilla.org/en-US/docs/Web/API/Range/surroundContents but then instead of highlighting text, it seems to just be removing it from the page.
#wOxxOm answered my question in a comment, but a setTimeout() is what worked. So for anyone else who might have a similar issue in the future:
// Finds the text selected in the page, spans it, and gives it a class
function getSelectedText(inputColor) {
var span = document.createElement('span');
span.setAttribute('class', inputColor);
if(document.getSelection) {
var selection = document.getSelection();
if(selection.rangeCount == true) {
var range = selection.getRangeAt(0).cloneRange();
setTimeout(function(){
range.surroundContents(span);
selection.removeAllRanges();
selection.addRange(range);
}, 100)
}
}
}
I'm having problems running an action on more than one line.
In practice I do not get the desired effect and <p> tags are completely emptied of their content. This is the simple code I use, but it only works on a line:
Try to look at code in action HERE .
Follow the instructions in the example to understand the real problem.
function press() {
if (document.getSelection) {
var sel = window.getSelection();
if (sel.rangeCount < 1) {
return;
}
var r = window.getSelection().getRangeAt(0);
var selectedText = r.toString(),
content = r.extractContents();
span = document.createElement('span'),
t = document.createTextNode(selectedText);
selectedText = '';
span.style.color = 'green';
span.appendChild(t);
r.insertNode(span);
window.getSelection().removeAllRanges();
}
}
<p>Select only me for first: i don't have problems</p>
<p>Also select me at the same time of first paragraph, now i have problems..</p>
<button onclick="press()">Press after selecting the text</button>
I am working in HTML with jquery.
I want to make a webpage to highlight some text lines (line nos 15, 22, 32) in that page at a time. This can be done by left click in mouse and drag that line, so that the text line is selected with blue background.
I am able to get the selected lines as follows using jquery,
function getText() {
var text = "";
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
text = document.selection.createRange().text;
}
console.log('text-----------'+text)
}
When I am clicking other line, first selected line was disappears. I need that line also be available. (In MSword, we can hold ctrl and drag the lines and it will be available)
For multiple selection, I know there is more plugins available in web. But I am looking for doing this selection using Javascript or jquery.
This is what I am looking for to do in my page, want to select texts and get them in my javascript function.
How may we do this?
This answer is combined of some issues.
Get the selection text
Mark it.
Copy to clipboard
It's not the full solution but there are all the parts.
So:
var output = '';
$('#test').mouseup(function () {
output += getSelectedText();
highlightSelected();
copyOutput();
$('#result').html(output);
});
function getSelectedText() {
if (window.getSelection) {
return window.getSelection().toString();
} else if (document.selection) {
return document.selection.createRange().text;
}
return '';
}
function highlightSelected() {
var SelRange;
if (window.getSelection) {
SelRange = window.getSelection().getRangeAt(0);
} else if (document.getSelection) {
SelRange = document.getSelection().getRangeAt(0);
} else if (document.selection) {
SelRange = document.selection.createRange();
}
if (SelRange.pasteHTML) {
SelRange.pasteHTML('<span class="hilited1">' + SelRange.text + '</span>');
}
else {
var newNode = $('<span class="hilited1" />')[0];
SelRange.surroundContents(newNode);
}
}
function copyOutput() {
var emailLink = document.querySelector('#result');
var range = document.createRange();
range.selectNode(emailLink);
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
try {
var successful = document.execCommand('copy');
} catch (err) {
console.log('Oops, unable to copy');
}
window.getSelection().removeAllRanges();
}
textarea {
width:100%;
height:150px;
}
.hilited1 {
background:red;
color:#fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">I am working in HTML with jquery.
I want to make a webpage to highlight some text lines (line nos 15, 22, 32) in that page at a time. This can be done by left click in mouse and drag that line, so that the text line is selected with blue background.
I am able to get the selected lines as follows using jquery,
</div>
<hr />
<div id="result"></div>
<hr />
<textarea placeholder="Try to paste here"></textarea>
I've created a simple tool so employees can personalize their company email signature. This tool creates some styled text with some bolded fonts and a bit of color, nothing fancy. If I then select the text and copy and paste it into my Gmail signature field all works well. It retains the formatting. However, I'd prefer to give the user the option of clicking a "Copy" button that copies the formatted content onto their clipboard.
I'm currently using ZeroClipboard to add the "copy to clipboard" functionality and it's working great. Thing is I don't know how to grab that formatted text. It just keeps copying the unformatted version. One thing I tried was adding a mouseDown listener to ZeroClipboard that selects the text like this:
function selectText() {
if (document.selection) {
var range = document.body.createTextRange();
range.moveToElementText(document.getElementById('clicktocopy'));
range.select();
}
else if (window.getSelection) {
var range = document.createRange();
range.selectNode(document.getElementById('clicktocopy'));
window.getSelection().addRange(range);
}
}
Then returns the selection like this:
function getText() {
if (window.getSelection) {
var range = window.getSelection();
return range.toString();
}
else {
if (document.selection.createRange) {
var range = document.selection.createRange();
return range.text;
}
}
}
However, this is only copying the unformatted text. Is it possible to copy the text formatted?
My formatted text is in a div with the id "results".
If you want an HTML string representing the current selection, the following function will do this (replacing your getText() function):
function getSelectionHtml() {
var html = "";
if (typeof window.getSelection != "undefined") {
var sel = window.getSelection();
if (sel.rangeCount) {
var container = document.createElement("div");
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
container.appendChild(sel.getRangeAt(i).cloneContents());
}
html = container.innerHTML;
}
} else if (typeof document.selection != "undefined") {
if (document.selection.type == "Text") {
html = document.selection.createRange().htmlText;
}
}
return html;
}
I'm trying to write a function that allows a contenteditable div to do some auto formatting while the user is typing in the div. So far I only manage to make it work in IE. Anyone can help me?
function formatOnKeyUp(){
if (window.getSelection) {
// ???????
} else if (document.selection) {
cursorPos=document.selection.createRange().duplicate();
clickx = cursorPos.getBoundingClientRect().left;
clicky = cursorPos.getBoundingClientRect().top;
}
text = document.getElementById('div1').innerHTML;
text = text.replace(/this/gm, "<i>this</i>");
// .... some other formating here...
document.getElementById('div1').innerHTML = text;
if (window.getSelection) {
// ????????
} else if (document.selection) {
cursorPos = document.body.createTextRange();
cursorPos.moveToPoint(clickx, clicky);
cursorPos.select();
}
}
You could use the selection save and restore module in my Rangy library, which uses invisible marker elements at the selection boundaries. I'd also suggest doing the replacement after a certain period of keboard inactivity rather than on every keyup event:
function formatText(el) {
// Save the selection
var savedSel = rangy.saveSelection();
// Do your formatting here
var text = el.innerHTML.replace(/this/gm, "<i>this</i>");
el.innerHTML = text;
// Restore the original selection
rangy.restoreSelection(savedSel);
}
var keyTimer = null, keyDelay = 500;
document.getElementById('div1').onkeyup = function() {
if (keyTimer) {
window.clearTimeout(keyTimer);
}
keyTimer = window.setTimeout(function() {
keyTimer = null;
formatText(document.getElementById('div1'));
}, keyDelay);
};
The cursor position and text range stuff looks particular to Microsoft's JScript.
If you're replacing text as someone types, why do you need that code?