Capture spellchecked words from browser input with JavaScript [duplicate] - javascript

How does one detect a spelling mistake inside a textarea in JavaScript? Is there an event associated with this? How do I access Chrome's spell-check suggestions for a misspelled word?

How do I access Chrome's spell-check suggestions for a misspelled word?
To the best of my knowledge, you cannot. To answer more fully, I'll also mention related issues:
There was once an unofficial Google spell-check API that has disappeared
You can download but not access Chrome's built in dictionary
There is no open API for Google's dictionary
Is there an event associated with this?
No, nor does the contextmenu event provide anything useful for this purpose: it has no spell-check information and you cannot read the list of context menu items (which may contain spelling suggestions). The change event also doesn't provide spell-check information.
How does one detect a spelling mistake inside a textarea in JavaScript?
You can either code this yourself or use a third party library. There are other Stack Overflow questions on this topic or you can search for yourself. Related Stack Overflow questions include:
Javascript Spell Checking Methods
javascript spell checker recommendations
Javascript based spell-checkers for web applications
Add spell check to my website
Need Client side spell checker for DIV
javascript spell checking

As the question seems a bit broad and open to interpretation (especially with the current bounty-'requirements'), I'll start by explaining how I interpret it and try to answer the subquestions in the process (Q/A style).
You seem to be asking:
"Google Chrome"/"Chromium" specific:
Q: if browser "Google Chrome"/"Chromium" exposes a spellcheck-API that you can interact with through the use of javascript in a common webpage
A: No, not really (at least not in the way you'd want).
There is a Chromium-specific Spellcheck API Proposal (from dec 2012).
Here are some parts of it:
Could this API be part of the web platform?
It is unlikely that spellchecking will become part of the web platform.
More importantly, it has only one method called 'loadDictionary':
loadDictionary( myDictionaryFile // string path or URL
, dictionaryFormat // enumerated string [ "hunspell" (concatentation of .aff and .dic files)
// , "text" (plain text)
// ]
) // returns int indicating success or an error code in loading the dictionary.
The point? Helping the community create custom dictionaries for Zulu, Klingon, etc. because approximately 20-30% of Spellcheck bugs-rapports were regarding unsupported languages.
Now let's not confuse Chrome's SpellCheck API (above) with Chrome/Webkit's SpellCheck API (hu? say what?):
Hironori Bono (a software engineer for Google Chrome) proposed an API around 2011 and some related bug rapports and a patch that was(/is still?) in Chrome.
void addSpellcheckRange( unsigned long start
, unsigned long length
, DOMStringList suggestions
// [, unsigned short options]
);
void removeSpellcheckRange(SpellcheckRange range);
Usage example:
var input = document.querySelector('input');
input.addSpellcheckRange( 4
, 9
, [ 'Chrome'
, 'Firefox'
, 'Opera'
, 'Internet Explorer'
]
);
Sources:
http://html5-demos.appspot.com/static/html5-whats-new/template/index.html#42 ,
http://peter.sh/experiments/spellcheck-api/ (you should be able to try it live there IF this API still works..)
The point? After contemplating over this a couple of day's it suddenly clicked: custom spell-check integration with the browser - using the browser's context-menu instead of blocking it and providing your own. So one could link that with an existing external spell-check library.
Above historical and experimental API's clearly never directly supported what you want to accomplish.
Q: if "Google Chrome"/"Chromium" spellcheck-API exposes an 'onSpellError' (-like) event on (for example) a textarea
A: As outlined above, it appears that Chrome doesn't have such an event.
HTM5 currently only exposes the ability to enable or disable spell-checking on spellcheck supported elements.
Q: how to access Chrome's spell-check suggestions for a misspelled word
A: As outlined above: it appears that you can't. It appears to be the same answer as for the almost duplicate-question: How can I access Chrome's spell-check dictionary?
It might be interesting to note that "TinyMCE's spellchecker was previously provided by 'hacking' a Chrome toolbar API owned by Google, against Google's own legal usage policies. This spellchecking service has been discontinued permanently.". Now if you search the web you probably can find how they did that, but it certainly doesn't seem the best way to go about it (and advocate it here).
Using javascript spell-check libraries you could however use Chrome's dictionaries (so you wouldn't need to maintain the dictionaries) but you would have to supply and ship these files together with your web-app (instead of fetching the installed ones in the browser).
General:
Q: How to detect a spelling mistake inside a textarea in JavaScript
A: Internet Explorer allows using the spellchecker
integrated into Microsoft Word via ActiveX as listed in the following
code snippet.
function CheckText(text) {
var result = new Array;
var app = new ActiveXObject('Word.Application');
var doc = app.Documents.Add();
doc.Content = text;
for (var i = 1; i <= doc.SpellingErrors.Count; i++) {
var spellingError = doc.SpellingErrors.Item(i);
for (var j = 1; j <= spellingError.Words.Count; j++) {
var word = spellingError.Words.Item(j);
var error = {};
error.word = word.Text;
error.start = word.Start;
error.length = word.Text.length;
error.suggestions = new Array;
var suggestions = word.GetSpellingSuggestions();
for (var k = 1; k <= suggestions.Count; k++) {
error.suggestions.push(suggestions.Item(k).Name);
}
result.push(error);
}
}
return result;
}
Source: https://lists.w3.org/Archives/Public/public-webapps/2011AprJun/0516.html
But IE/ActiveX/MS-Word isn't really what you have asked for, neither is it very cross platform/browser, that leaves us with local javascript spell-check libraries:
Javascript Spell Checking Methods
http://code.google.com/p/bjspell/
http://www.javascriptspellcheck.com/
http://ejohn.org/blog/revised-javascript-dictionary-search/
Etc.
Comparing/explaining them is really outside the scope of this answer.
It is worth noting what format of dictionary you wish to use!
Alternatively one could use an external spellcheck API service (where a server handles the data and you'd communicate with it using AJAX).
Obviously you'd need to take privacy matters into account!
The bounty-'requirements' ask for:
Q: definitive proof
A: I should have found something more regarding the subject than some esoteric experimental features. Neither do I see libraries that try to shim their functionality into some (upcoming) standardized method/event identifiers etc.
As noted, popular libraries like TinyMCE also currently have no other solution.
In the 'living standard'/'the world is our playground' mentality my answer could very well already be outdated when I press the 'submit'-button. But even then I wouldn't recommend such an experimental feature in the near future on a 'production' level website/interface.
Q: and obtaining a good answer explaining how to achieve this
(chrome specific or in general? Spell-check suggestions or detecting that there is a typo?)
A: Other than the above, I can't think of anything (other than libraries that web-developers currently use (see 4)).
Hope this helps!

There is not an API for accessing Chrome's spellcheck suggestions, nor are there natively any events fired when words are mistyped. However, events could be implemented.
I have no idea what your use-case is for this functionality, but I put together a demonstration using montanaflynn's Spellcheck API on MashApe. The demo watches a text area, and when the user pauses typing, it sends the text via the API to be tested. The API returns JSON containing the original string, the suggested corrected string, and an object containing the corrected words and their suggested replacements.
The suggestions are displayed below the textarea. When suggestions are hovered, the mistyped word is highlighted. When clicked, the typo is replaced with the suggestion.
I also added a shuffling function, that scrambles the words in the string before sending it, to add a layer of privacy to the use of the API (it uses SSL also). Neither the API nor Chrome use context-based suggestions, so the shuffling doesn't alter the results.
Here's a link to the CodePen: http://codepen.io/aecend/pen/rOebQq
And here is the code:
CSS
<style>
* {
font-family: sans-serif;
}
textarea {
margin-bottom: 10px;
width: 500px;
height: 300px;
padding: 10px;
}
.words {
width: 500px;
}
.word {
display: inline-block;
padding: 2px 5px 1px 5px;
border-radius: 2px;
background: #00B1E6;
color: white;
margin: 2px;
cursor: pointer;
}
</style>
HTML
<textarea id="text" placeholder="Type something here..."></textarea>
<div id="words"></div>
JavaScript
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
;(function(){
"use strict";
var words = document.getElementById("words"),
input = document.getElementById("text"),
timeout, xhr;
input.addEventListener("keyup", function(e){
if (timeout) clearTimeout(timeout);
if (!this.value.trim()) words.innerHTML = '';
timeout = setTimeout(function() {
var test_phrase = shuffle_words( input.value );
spell_check(test_phrase);
timeout = null;
}, 500);
});
function shuffle_words(inp) {
inp = inp.replace(/\s+/g, ' ');
var arr = inp.split(" "),
n = arr.length;
while (n > 0) {
var i = Math.floor(Math.random() * n--),
t = arr[n];
arr[n] = arr[i];
arr[i] = t;
}
return arr.join(' ');
}
function spell_check(text){
if (xhr) xhr.abort();
xhr = $.ajax({
url: 'https://montanaflynn-spellcheck.p.mashape.com/check/',
headers: {
'X-Mashape-Key': 'U3ogA8RAAMmshGOJkNxkTBbuYYRTp1gMAuGjsniThZuaoKIyaj',
'Accept': 'application/json'
},
data: {
'text': text
},
cache: false,
success: function(result){
xhr = null;
suggest_words(result);
}
});
}
function suggest_words(obj){
if (!obj.corrections) return;
words.innerHTML = '';
for (var key in obj.corrections) {
if (obj.corrections.hasOwnProperty(key)) {
var div = document.createElement("div");
div.className = "word";
div.innerHTML = obj.corrections[key][0];
div.orig = key;
div.onmouseover = function() {
var start = input.value.indexOf(this.orig);
input.selectionStart = start;
input.selectionEnd = start + this.orig.length;
};
div.onmouseout = function() {
var len = input.value.length;
input.selectionStart = len;
input.selectionEnd = len;
}
div.onclick = function() {
input.value = input.value.replace(this.orig, this.innerHTML);
this.parentNode.removeChild(this);
}
words.appendChild(div);
}
}
}
})();
</script>
I only used jQuery to simplify the AJAX request for this demonstration. This could easily be done in vanilla JS.

You can disable internal browser spellcheck and integrate any other opensource spellcheck library, for example
JavaScript SpellCheck. It contains all events you may need for deep integration, check the API page.

Related

How to access Chrome spell-check suggestions in JavaScript

How does one detect a spelling mistake inside a textarea in JavaScript? Is there an event associated with this? How do I access Chrome's spell-check suggestions for a misspelled word?
How do I access Chrome's spell-check suggestions for a misspelled word?
To the best of my knowledge, you cannot. To answer more fully, I'll also mention related issues:
There was once an unofficial Google spell-check API that has disappeared
You can download but not access Chrome's built in dictionary
There is no open API for Google's dictionary
Is there an event associated with this?
No, nor does the contextmenu event provide anything useful for this purpose: it has no spell-check information and you cannot read the list of context menu items (which may contain spelling suggestions). The change event also doesn't provide spell-check information.
How does one detect a spelling mistake inside a textarea in JavaScript?
You can either code this yourself or use a third party library. There are other Stack Overflow questions on this topic or you can search for yourself. Related Stack Overflow questions include:
Javascript Spell Checking Methods
javascript spell checker recommendations
Javascript based spell-checkers for web applications
Add spell check to my website
Need Client side spell checker for DIV
javascript spell checking
As the question seems a bit broad and open to interpretation (especially with the current bounty-'requirements'), I'll start by explaining how I interpret it and try to answer the subquestions in the process (Q/A style).
You seem to be asking:
"Google Chrome"/"Chromium" specific:
Q: if browser "Google Chrome"/"Chromium" exposes a spellcheck-API that you can interact with through the use of javascript in a common webpage
A: No, not really (at least not in the way you'd want).
There is a Chromium-specific Spellcheck API Proposal (from dec 2012).
Here are some parts of it:
Could this API be part of the web platform?
It is unlikely that spellchecking will become part of the web platform.
More importantly, it has only one method called 'loadDictionary':
loadDictionary( myDictionaryFile // string path or URL
, dictionaryFormat // enumerated string [ "hunspell" (concatentation of .aff and .dic files)
// , "text" (plain text)
// ]
) // returns int indicating success or an error code in loading the dictionary.
The point? Helping the community create custom dictionaries for Zulu, Klingon, etc. because approximately 20-30% of Spellcheck bugs-rapports were regarding unsupported languages.
Now let's not confuse Chrome's SpellCheck API (above) with Chrome/Webkit's SpellCheck API (hu? say what?):
Hironori Bono (a software engineer for Google Chrome) proposed an API around 2011 and some related bug rapports and a patch that was(/is still?) in Chrome.
void addSpellcheckRange( unsigned long start
, unsigned long length
, DOMStringList suggestions
// [, unsigned short options]
);
void removeSpellcheckRange(SpellcheckRange range);
Usage example:
var input = document.querySelector('input');
input.addSpellcheckRange( 4
, 9
, [ 'Chrome'
, 'Firefox'
, 'Opera'
, 'Internet Explorer'
]
);
Sources:
http://html5-demos.appspot.com/static/html5-whats-new/template/index.html#42 ,
http://peter.sh/experiments/spellcheck-api/ (you should be able to try it live there IF this API still works..)
The point? After contemplating over this a couple of day's it suddenly clicked: custom spell-check integration with the browser - using the browser's context-menu instead of blocking it and providing your own. So one could link that with an existing external spell-check library.
Above historical and experimental API's clearly never directly supported what you want to accomplish.
Q: if "Google Chrome"/"Chromium" spellcheck-API exposes an 'onSpellError' (-like) event on (for example) a textarea
A: As outlined above, it appears that Chrome doesn't have such an event.
HTM5 currently only exposes the ability to enable or disable spell-checking on spellcheck supported elements.
Q: how to access Chrome's spell-check suggestions for a misspelled word
A: As outlined above: it appears that you can't. It appears to be the same answer as for the almost duplicate-question: How can I access Chrome's spell-check dictionary?
It might be interesting to note that "TinyMCE's spellchecker was previously provided by 'hacking' a Chrome toolbar API owned by Google, against Google's own legal usage policies. This spellchecking service has been discontinued permanently.". Now if you search the web you probably can find how they did that, but it certainly doesn't seem the best way to go about it (and advocate it here).
Using javascript spell-check libraries you could however use Chrome's dictionaries (so you wouldn't need to maintain the dictionaries) but you would have to supply and ship these files together with your web-app (instead of fetching the installed ones in the browser).
General:
Q: How to detect a spelling mistake inside a textarea in JavaScript
A: Internet Explorer allows using the spellchecker
integrated into Microsoft Word via ActiveX as listed in the following
code snippet.
function CheckText(text) {
var result = new Array;
var app = new ActiveXObject('Word.Application');
var doc = app.Documents.Add();
doc.Content = text;
for (var i = 1; i <= doc.SpellingErrors.Count; i++) {
var spellingError = doc.SpellingErrors.Item(i);
for (var j = 1; j <= spellingError.Words.Count; j++) {
var word = spellingError.Words.Item(j);
var error = {};
error.word = word.Text;
error.start = word.Start;
error.length = word.Text.length;
error.suggestions = new Array;
var suggestions = word.GetSpellingSuggestions();
for (var k = 1; k <= suggestions.Count; k++) {
error.suggestions.push(suggestions.Item(k).Name);
}
result.push(error);
}
}
return result;
}
Source: https://lists.w3.org/Archives/Public/public-webapps/2011AprJun/0516.html
But IE/ActiveX/MS-Word isn't really what you have asked for, neither is it very cross platform/browser, that leaves us with local javascript spell-check libraries:
Javascript Spell Checking Methods
http://code.google.com/p/bjspell/
http://www.javascriptspellcheck.com/
http://ejohn.org/blog/revised-javascript-dictionary-search/
Etc.
Comparing/explaining them is really outside the scope of this answer.
It is worth noting what format of dictionary you wish to use!
Alternatively one could use an external spellcheck API service (where a server handles the data and you'd communicate with it using AJAX).
Obviously you'd need to take privacy matters into account!
The bounty-'requirements' ask for:
Q: definitive proof
A: I should have found something more regarding the subject than some esoteric experimental features. Neither do I see libraries that try to shim their functionality into some (upcoming) standardized method/event identifiers etc.
As noted, popular libraries like TinyMCE also currently have no other solution.
In the 'living standard'/'the world is our playground' mentality my answer could very well already be outdated when I press the 'submit'-button. But even then I wouldn't recommend such an experimental feature in the near future on a 'production' level website/interface.
Q: and obtaining a good answer explaining how to achieve this
(chrome specific or in general? Spell-check suggestions or detecting that there is a typo?)
A: Other than the above, I can't think of anything (other than libraries that web-developers currently use (see 4)).
Hope this helps!
There is not an API for accessing Chrome's spellcheck suggestions, nor are there natively any events fired when words are mistyped. However, events could be implemented.
I have no idea what your use-case is for this functionality, but I put together a demonstration using montanaflynn's Spellcheck API on MashApe. The demo watches a text area, and when the user pauses typing, it sends the text via the API to be tested. The API returns JSON containing the original string, the suggested corrected string, and an object containing the corrected words and their suggested replacements.
The suggestions are displayed below the textarea. When suggestions are hovered, the mistyped word is highlighted. When clicked, the typo is replaced with the suggestion.
I also added a shuffling function, that scrambles the words in the string before sending it, to add a layer of privacy to the use of the API (it uses SSL also). Neither the API nor Chrome use context-based suggestions, so the shuffling doesn't alter the results.
Here's a link to the CodePen: http://codepen.io/aecend/pen/rOebQq
And here is the code:
CSS
<style>
* {
font-family: sans-serif;
}
textarea {
margin-bottom: 10px;
width: 500px;
height: 300px;
padding: 10px;
}
.words {
width: 500px;
}
.word {
display: inline-block;
padding: 2px 5px 1px 5px;
border-radius: 2px;
background: #00B1E6;
color: white;
margin: 2px;
cursor: pointer;
}
</style>
HTML
<textarea id="text" placeholder="Type something here..."></textarea>
<div id="words"></div>
JavaScript
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
;(function(){
"use strict";
var words = document.getElementById("words"),
input = document.getElementById("text"),
timeout, xhr;
input.addEventListener("keyup", function(e){
if (timeout) clearTimeout(timeout);
if (!this.value.trim()) words.innerHTML = '';
timeout = setTimeout(function() {
var test_phrase = shuffle_words( input.value );
spell_check(test_phrase);
timeout = null;
}, 500);
});
function shuffle_words(inp) {
inp = inp.replace(/\s+/g, ' ');
var arr = inp.split(" "),
n = arr.length;
while (n > 0) {
var i = Math.floor(Math.random() * n--),
t = arr[n];
arr[n] = arr[i];
arr[i] = t;
}
return arr.join(' ');
}
function spell_check(text){
if (xhr) xhr.abort();
xhr = $.ajax({
url: 'https://montanaflynn-spellcheck.p.mashape.com/check/',
headers: {
'X-Mashape-Key': 'U3ogA8RAAMmshGOJkNxkTBbuYYRTp1gMAuGjsniThZuaoKIyaj',
'Accept': 'application/json'
},
data: {
'text': text
},
cache: false,
success: function(result){
xhr = null;
suggest_words(result);
}
});
}
function suggest_words(obj){
if (!obj.corrections) return;
words.innerHTML = '';
for (var key in obj.corrections) {
if (obj.corrections.hasOwnProperty(key)) {
var div = document.createElement("div");
div.className = "word";
div.innerHTML = obj.corrections[key][0];
div.orig = key;
div.onmouseover = function() {
var start = input.value.indexOf(this.orig);
input.selectionStart = start;
input.selectionEnd = start + this.orig.length;
};
div.onmouseout = function() {
var len = input.value.length;
input.selectionStart = len;
input.selectionEnd = len;
}
div.onclick = function() {
input.value = input.value.replace(this.orig, this.innerHTML);
this.parentNode.removeChild(this);
}
words.appendChild(div);
}
}
}
})();
</script>
I only used jQuery to simplify the AJAX request for this demonstration. This could easily be done in vanilla JS.
You can disable internal browser spellcheck and integrate any other opensource spellcheck library, for example
JavaScript SpellCheck. It contains all events you may need for deep integration, check the API page.

How to get the full list of Modernizr features

Is there any way to get a list of all features detected by Modernizr?
The current naming of features is very unintuitive, for example to check for feature "canvas" you just have to call Modernizr.canvas but in order to check for "forms-placeholder" or "forms_placeholder" (it depends on whether you check for the feature's name on the page or in the generated code) you have to call Modernizr.placeholder
There seems to be no rule in the naming of features. I couldn't even find a complete reference of all these features, especially the "non-core" ones. The documentation on modernizr.com is very poor. It also lacks a good tutorial. All I can do is simply guess it's names, since only some of them are included as the class names for the <html> tag (for example, you won't find "Input Types" or "Input Attributes" there).
All I need is to call some functions only when specific feature is supported, for example:
if(Modernizr.canvas){
// draw canvas
}
I tried to detect whether the browser supports .toDataURL('image/png') function, but the Modernizr script returns only "todataurljpeg" and "todataurlwebp", even though the "todataurlpng" is somwhere in there.
How can I retrieve all the Modernizer.features names via JavaScript? Any links to some good references or tutorials will be appreciated (obviously not the ones from the Modernizr home page).
I think your biggest problem is you're mixing up your versions. In the current stable tag, 2.8.1, this is the test for todataurl:
// canvas.toDataURL type support
// http://www.w3.org/TR/html5/the-canvas-element.html#dom-canvas-todataurl
// This test is asynchronous. Watch out.
(function () {
if (!Modernizr.canvas) {
return false;
}
var image = new Image(),
canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d');
image.onload = function() {
ctx.drawImage(image, 0, 0);
Modernizr.addTest('todataurljpeg', function() {
return canvas.toDataURL('image/jpeg').indexOf('data:image/jpeg') === 0;
});
Modernizr.addTest('todataurlwebp', function() {
return canvas.toDataURL('image/webp').indexOf('data:image/webp') === 0;
});
};
image.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAACklEQVR4nGMAAQAABQABDQottAAAAABJRU5ErkJggg==';
}());
(source: https://github.com/Modernizr/Modernizr/blob/v2.8.1/feature-detects/canvas-todataurl-type.js)
You'll notice in particular that 'todataurlpng' is not present.
Now, here's the test in master (3.0 beta):
/*!
{
"name": "canvas.toDataURL type support",
"property": ["todataurljpeg", "todataurlpng", "todataurlwebp"],
"tags": ["canvas"],
"builderAliases": ["canvas_todataurl_type"],
"async" : false,
"notes": [{
"name": "HTML5 Spec",
"href": "http://www.w3.org/TR/html5/the-canvas-element.html#dom-canvas-todataurl"
}]
}
!*/
define(['Modernizr', 'createElement', 'test/canvas'], function( Modernizr, createElement ) {
var canvas = createElement('canvas');
Modernizr.addTest('todataurljpeg', function() {
return !!Modernizr.canvas && canvas.toDataURL('image/jpeg').indexOf('data:image/jpeg') === 0;
});
Modernizr.addTest('todataurlpng', function() {
return !!Modernizr.canvas && canvas.toDataURL('image/png').indexOf('data:image/png') === 0;
});
Modernizr.addTest('todataurlwebp', function() {
return !!Modernizr.canvas && canvas.toDataURL('image/webp').indexOf('data:image/webp') === 0;
});
});
(source: https://github.com/Modernizr/Modernizr/blob/master/feature-detects/canvas/todataurl.js)
There it is!
The docs are better than you think, but 3.0 beta is a major rewrite and the docs have not been updated (mostly because it hasn't actually been released, yet). Just keep in mind that if you see something you think should be there or isn't mentioned in the docs, it's probably something new in the beta.
As for a list of all the feature detections, there's the docs, which is still your safest bet. I also found this nifty site, but it appears that, despite what it says in the description, the tool is referencing the master branch, and is thus, pulling from 3.0 beta with all the new and changed detects. So it might be a little off-putting for now.

Copy to clipboard without Flash

I found many solutions for copying to the clipboard, but they all either with flash, or for websites side.
I'm looking for method copy to clipboard automatically, without flash and for user side, it's for userscripts and of course cross-browser.
Without flash, it's simply not possible in most browsers. The user's clipboard is a security-relevant resource since it could contain things like passwords or credit card numbers. Thus, browsers rightly don't allow Javascript access to it (some allow it with a warning shown that the user has confirm, or with signed Javascript code, but none of that is cross-browser).
I had tryed the flash solution and I don't liked too. Too complex and too slow. What I did was to create a textarea, put the data into that and use the browser "CTRL + C" behavior.
The jQuery javascript part:
// catch the "ctrl" combination keydown
$.ctrl = function(key, callback, args) {
$(document).keydown(function(e) {
if(!args) args=[]; // IE barks when args is null
if(e.keyCode == key && e.ctrlKey) {
callback.apply(this, args);
return false;
}
});
};
// put your data on the textarea and select all
var performCopy = function() {
var textArea = $("#textArea1");
textArea.text('PUT THE TEXT TO COPY HERE. CAN BE A FUNCTION.');
textArea[0].focus();
textArea[0].select();
};
// bind CTRL + C
$.ctrl('C'.charCodeAt(0), performCopy);
The HTML part:
<textarea id="textArea1"></textarea>
Now, put what do you want to copy in 'PUT THE TEXT TO COPY HERE. CAN BE A FUNCTION.' area.
Works fine for me me. You just have to make one CTRL+C combination. The only drawback is that you are going to have an ugly textarea displayed in you site. If you use the style="display:none" the copy solution will not work.
clipboard.js has just been released to copy to clipboard without the need of Flash
See it in action here > http://zenorocha.github.io/clipboard.js/#example-action
It's finally here! (As long as you don't support Safari or IE8... -_- )
You can now actually handle clipboard actions without Flash. Here's the relevant documentation:
https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand
https://developers.google.com/web/updates/2015/04/cut-and-copy-commands?hl=en
https://msdn.microsoft.com/en-us/library/hh801227%28v=vs.85%29.aspx#copy
While waiting impatiently for Xbrowser support of the Clipboard API...
This will work beautifully in Chrome, Firefox, Edge, IE
IE will only prompt the user once to access the Clipboard.
Safari (5.1 at the time of writing) does not support execCommand for copy/cut
/**
* CLIPBOARD
* https://stackoverflow.com/a/33337109/383904
*/
const clip = e => {
e.preventDefault();
const cont = e.target.innerHTML;
const area = document.createElement("textarea");
area.value = e.target.innerHTML; // or use .textContent
document.body.appendChild(area);
area.select();
if(document.execCommand('copy')) console.log("Copied to clipboard");
else prompt("Copy to clipboard:\nSelect, Cmd+C, Enter", cont); // Saf, Other
area.remove();
};
[...document.querySelectorAll(".clip")].forEach(el =>
el.addEventListener("click", clip)
);
<a class="clip" href="#!">Click an item to copy</a><br>
<a class="clip" href="#!"><i>Lorem</i></a><br>
<a class="clip" href="#!"><b>IPSUM</b></a><br>
<textarea placeholder="Paste here to test"></textarea>
All browsers (except Firefox which is able to only handle mime type "plain/text" as far as I've tested) have not implemented the Clipboard API. I.e, trying to read the clipboard event in Chrome using
var clipboardEvent = new ClipboardEvent("copy", {
dataType: "plain/text",
data: "Text to be sent to clipboard"
});
throws: Uncaught TypeError: Illegal constructor
The best resource of the unbelievable mess that's happening among browsers and the Clipboard can be seen here (caniuse.com) (→ Follow the comments under "Notes").
MDN says that basic support is "(YES)" for all browsers which is inaccurate cause one would expect at least the API to work, at all.
You can use a clipboard local to the HTML page. This allows you to copy/cut/paste content WITHIN the HTML page, but not from/to third party applications or between two HTML pages.
This is how you can write a custom function to do this (tested in chrome and firefox):
Here is the FIDDLE that demonstrates how you can do this.
I will also paste the fiddle here for reference.
HTML
<p id="textToCopy">This is the text to be copied</p>
<input id="inputNode" type="text" placeholder="Copied text will be pasted here" /> <br/>
copy
cut
paste
JS
function Clipboard() {
/* Here we're hardcoding the range of the copy
and paste. Change to achieve desire behavior. You can
get the range for a user selection using
window.getSelection or document.selection on Opera*/
this.oRange = document.createRange();
var textNode = document.getElementById("textToCopy");
var inputNode = document.getElementById("inputNode");
this.oRange.setStart(textNode,0);
this.oRange.setEndAfter(textNode);
/* --------------------------------- */
}
Clipboard.prototype.copy = function() {
this.oFragment= this.oRange.cloneContents();
};
Clipboard.prototype.cut = function() {
this.oFragment = this.oRange.extractContents();
};
Clipboard.prototype.paste = function() {
var cloneFragment=this.oFragment.cloneNode(true)
inputNode.value = cloneFragment.textContent;
};
window.cb = new Clipboard();
document.execCommand('copy') will do what you want. But there was no directly usable examples in this thread without cruft, so here it is:
var textNode = document.querySelector('p').firstChild
var range = document.createRange()
var sel = window.getSelection()
range.setStart(textNode, 0)
range.setEndAfter(textNode)
sel.removeAllRanges()
sel.addRange(range)
document.execCommand('copy')
There is not way around, you have to use flash. There is a JQuery plugin called jquery.copy that provided cross browser copy and paste by using a flash (swf) file. This is similar to how the syntax highlighter on my blog works.
Once you reference the jquery.copy.js file all you need to do to push data into the clipboard is run the following:
$.copy("some text to copy");
Nice and easy ;)

Detecting support for VML, help applying a previous post

I found the following in a previous post but need some help with it:
// For VML detection, here's what google maps does (search for "function Xd"):
function supportsVml() {
if (typeof supportsVml.supported == "undefined") {
var a = document.body.appendChild(document.createElement('div'));
a.innerHTML = '<v:shape id="vml_flag1" adj="1" />';
var b = a.firstChild;
b.style.behavior = "url(#default#VML)";
supportsVml.supported = b ? typeof b.adj == "object": true;
a.parentNode.removeChild(a);
}
return supportsVml.supported;
}
I would like to use the code to divert users to an alternative page when VML is not supported. Please could somebody show me how to write and implement the code to divert, say, to a page called alternative.html.
I have some knowledge of javascript but not this level!
Thanks.
You can just make a call to that function provided by Google, and it will return true if VML is supported and false if not. Don't forget, you will still need to add the xmlns for VML somewhere in your HTML.
if (!supportsVml())
window.location = "http://somedomain.com/no-vml.html";
Also, I would recommend using a cross-browser library for drawing vector graphics. There's a few to choose from in this blog post: Canvas/SVG/VML Drawing Roundup.
VML is only supported in Internet Explorer (as of 5.0) and is not supported in any other browser. So checking for IE should be just enough. This can be done in many ways, for example: !!document.namespaces

using javascript to track another javascript script?

I was just wondering whether there are any way (libraries, frameworks, tutorials) to do javascript tracking with another script? Basically, i want to track as the user work with the site, which function gets executed with what parameters and so on, as detailed as possible.
thanks a lot!
The extent of detail you're expecting will be challenging for any solution to gather and report on without severely slowing down your scripts -- consider that, for every call, at least 1 other call would need to occur to gather this.
You'd be better to pick a few key events (mouse clicks, etc.) and track only a few details (such as time) for them. If you're using ajax, keep JavaScript and the browser oblivious and just track this on server-side.
There's a few options but I'm not sure if there are any "great" ones. I take it Firebug/IE Dev toolbar profiling won't work because you are trying to track remote user's actions.
So, one option (I'm not highly recommending for production purposes), will work in some but not all browsers.
Essentially you overwrite every function, with a wrapper that you then inject your logging.
(I haven't tested this, trying to recall it from memory... hopefully in "pseudo code" you get the idea...)
//e.g. get all functions defined on the global window object
function logAll(){
var funcs = [];
var oldFunc;
for(var i in window){
try {
if(typeof(window[i]) == 'function'){
if(i != 'logAll'){
funcs.push(i);
}
}
} catch(ex){
//handle as desired
}
}
var x;
for(var i in funcs){
x = '_' + new Date().getTime();
window[x] = window[i];//save the old function as new function
//redefine original
window[i] = function(){
//do your logging here...
//then call the real function (and pass all params along)
call(window[x]);
};
}
};

Categories