Copy to clipboard with Javascript in Firefox - javascript

I really need a way to copy some text to the OS clipboard in Firefox.
Know it is easy in IE and not possible in Chrome and Opera unless flash is used. Because of different reasons I am unable to use the flash solution!
Had it working in the past but now the netscape.security.PrivilegeManager.enablePrivilege is protected as far as I can figure out (since ver. 17).
It looks as if it is still possible according to this article:
https://developer.mozilla.org/en-US/docs/Using_the_Clipboard
Believe it is still necessary to enable the possibility in the user.js file like this
user_pref("capability.policy.policynames", "allowclipboard");
user_pref("capability.policy.allowclipboard.sites", "http://");
user_pref("capability.policy.allowclipboard.Clipboard.cutcopy", "allAccess");
But how shall I do it? Have made some test without great success and think there is no guide on the web that explain how it shall be done in a generic way. E.g. a simple guide about how to enable javascript access to the clipboard. Hopefully also a guide that can be used by the novice user. Like to do it and post it here but need a working solution first.
According to the web there are 2 solutions for copy to clipboard;
document.execCommand("copy", false, null)
and
var gClipboardHelper = Components.classes["#mozilla.org/widget/clipboardhelper;1"].getService(Components.interfaces.nsIClipboardHelper);
gClipboardHelper.copyString("Put me on the clipboard, please.");
Both generate a failure with my first try.
The solution below need the user to press CTRL+C and I need a solution where the text shall copy based on the press of a button (many on a single page).
https://stackoverflow.com/questions/4344325/copy-to-clipboard-on-firefox-and-google-chrome/11346026#11346026
My old solution was like this:
var clip = Components.classes['#mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
if(clip)
{
var trans = Components.classes['#mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
if(trans)
{
var str = new Object();
var len = new Object();
var str = Components.classes["#mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
if(str)
{
var clipid=Components.interfaces.nsIClipboard;
if(clipid)
{
str.data = cliptext;
trans.addDataFlavor('text/unicode');
trans.setTransferData("text/unicode", str, cliptext.length*2);
clip.setData(trans, null, clipid.kGlobalClipboard); // No return value
return 0;
}
}
}
}
Components.classes is undefined in unprivileged code (not add-on etc) so I do not believe any solution with this will work any more. One option is to make an add-on that will execute in privileged code area and send the text that shall be copied to this add-on for it to handle the copy to the OS clipboard (nice new possible project).
This only leave document.execCommand("copy", false, null) in the field as a stand alone solution.
Tried this code and it does not copy anything to the OS clipboard - but do not generate any errors btw.
var pre = document.getElementById('pcryptcopytext');
if(!pre)
{
pre = document.createElement("pre");
pre.setAttribute('id', 'pcryptcopytext');
pre.setAttribute('style', 'opacity: 0; position: absolute; top: -10000px; right: 0;');
document.body.appendChild(pre);
}
pre.innerHTML = cliptext;
pre.contentEditable = true;
//pre.unselectable = "off";
//pre.focus();
if (document.createRange)
{
var rng = document.createRange();
rng.selectNodeContents(pre);
document.execCommand("copy", false, null);
document.body.removeChild(pre);
}
So, anybody got a working solution?

Looks like this is not supported any more, and there is no replacement :(
https://support.mozilla.org/en-US/questions/977068#answer-500083
Maybe making some noise in a Firefox bug will help us get a (safe) solution.

Solved by creating a Firefox Add-on that exposes the clipboard object: https://github.com/myplaceonline/myplaceonline_ffclipboard
Example:
if (window.ffclipboard) {
window.ffclipboard.setText("clipboard text");
}

You can use firefox navigator object
navigator.clipboard.writeText("text you want to copy").then(() => {
// on success
}, (e) => {
// on error
});
document.execCommand("copy");

Related

Check if text has error of typing [duplicate]

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 create ActiveX object in asp.net

How can i create ActiveX Object in java script using asp.net.what i need requirements to create that ActiveX object if i use any DLL to create that object and how can i create can anyone provide description of to create ActiveX object
My Tried code is:
<script lang="javascript" type="text/javascript">
function getSize()
{
var oas = new ActiveXObject("Scripting.FileSystemObject");
var d = document.getElementById('b').value;
var e = oas.getFile(d);
var f = e.size;
return(f);
}
function checkFileType()
{
var path = document.getElementById('file1').value;
var Index = path.lastIndexOf(".");
var length = path.length;
var filetype = path.substring(Index,length)
if ((filetype == ".doc") ||(filetype == ".pdf") ||(filetype == ".jpg") ||(filetype == ".gif") ||(filetype == ".xls")||(filetype==".odt"))
{
var x = getSize(); if (x > 5242880)
{
alert('only upto 5 MB file is allowed');
return false;
}
}
else
{
alert('Only .doc, .pdf, .jpg, .gif, .xls is allowed');return false;
}
}
</script>
<form id="form1" runat="server">
<input type="file" name="b" id="file1" onchange="return checkFileType();" />
<div>
</div>
</form>
In the above code i am getting this line in code
" var oas = new ActiveXObject("Scripting.FileSystemObject");" getting Exception is "0x800a01ad - JavaScript runtime error: Automation server can't create object".
Can anyone tell me to how can i create ActiveX object properly and what i need setting and which DLL's i use and all can anyone help me out.
Thank You
This validation is not a supported method in all the browsers.
Anyway, for IE9 or below (where .files is not supported) you can use this. To use this method, you will need to enable activex object in IE.
Go to Internet Options->Security Tab. Select trusted website, and click Sites button. It will give you an option to add the url. Add the url of your site, and save. Then click on the button saying "custom levels". It will open a list of options. Find the one saying "Initialize and script activex controls not marked as safe" and enable it.
Save and close the dialog boxes, and refresh your webpage.
Edit:
Few notes:
This is extremely unsecure method, so I would suggest improving compatibility and saying no to anything below IE9.
Secondly, this is something you have to enable on every single user's machine. Otherwise, that line will always throw an exception.
So, if you have to stick to IE8 or lower, and have control over your userbase, then only use this. Otherwise, just use flash upload method for IE browsers. Your users might hate installing flash, but there is nothing you can do.
P.S. I was doing this same thing about an hour ago. Lucky for you, I did all the research. :)
Edit: On a secondary note, can someone help me figure out how to get rid of XML dataislands without major rewrite? That is the only thing stopping me from saying goodbye to IE6.

Get selected message data in Thunderbird extension

I need to get some e-mail message data in my Thunderbird extension. I found this example on MDN (https://developer.mozilla.org/en-US/docs/XPCOM_Interface_Reference/nsIMsgMessageService):
var content = "";
var MessageURI = GetFirstSelectedMessage();
var MsgService = messenger.messageServiceFromURI(MessageURI);
var MsgStream = Components.classes["#mozilla.org/network/sync-stream-listener;1"].createInstance();
var consumer = MsgStream.QueryInterface(Components.interfaces.nsIInputStream);
var ScriptInput = Components.classes["#mozilla.org/scriptableinputstream;1"].createInstance();
var ScriptInputStream = ScriptInput.QueryInterface(Components.interfaces.nsIScriptableInputStream);
ScriptInputStream.init(consumer);
try {
MsgService.streamMessage(MessageURI, MsgStream, msgWindow, null, false, null);
} catch (ex) {
alert("error: "+ex)
}
ScriptInputStream .available();
while (ScriptInputStream .available()) {
content = content + ScriptInputStream .read(512);
}
alert(content);
However, when I run it I get the following error:
Timestamp: 2013.06.21. 14:47:21
Error: ReferenceError: GetFirstSelectedMessage is not defined
Source File: chrome://edus_extension/content/messengerOverlay.js
Line: 90
What is this 'GetFirstSelectedMessage' function and how can I get message URI without using it?
This documentation looks fairly outdated. I would suggest:
using gFolderDisplay.selectedMessage (try typing top.opener.gFolderDisplay.selectedMessage in the Error Console),
reading some recent code that uses Services and MailServices so as to simplify your code.
That being said, I don't know what you're trying to achieve but:
you'd certainly be better off using a wrapper such as MsgHdrToMimeMessage (self-reference: http://blog.xulforum.org/index.php?post/2011/01/03/An-overview-of-Thunderbird-Conversations)
if you absolutely, absolutely need to get the raw contents of the message, http://mxr.mozilla.org/comm-central/source/mailnews/db/gloda/modules/mimemsg.js#223 has an example on how to do that (it's the implementation of the said MsgHdrToMimeMessage; by simplifying it, you should be able to get directly the raw data of the message).
Good luck with that, once you get a working sample, please add it to the MDN wiki!
Cheers,
jonathan

Autocompletion for Ace Editor

OK, so here's the deal:
I'm using Ace Editor
The app the editor is integrated in, is written Objective-C/Cocoa
I need AutoCompletion (for a given set of keywords)
Now, here's the catch :
I know AutoCompletion is not yet natively supported
I know of some attempts by others (e.g. Codiad IDE, Gherkin, Alloy-UI), some making use of Jquery UI Autocomplete - but I still cannot figure out how this could be adapted to an existing Ace setup
I'm still not sure if I should go for a JS-oriented solution or just use Objective-C/Cocoa for that
Any help would be more than appreciated.
AutoCompletion can be achieved in ace editor..
Code :
var editor = ace.edit('editor');
editor.setTheme("ace/theme/eclipse");
editor.getSession().setMode("ace/mode/java");
editor.setShowInvisibles(true);
editor.setDisplayIndentGuides(true);
editor.getSession().setUseWrapMode(true);
var jsonUrl = "JSON/Components/proce.json";
//the url where the json file with the suggestions is present
var langTools = ace.require("ace/ext/language_tools");
editor.setOptions({enableBasicAutocompletion: true});
var rhymeCompleter = {
getCompletions: function(editor, session, pos, prefix, callback) {
if (prefix.length === 0) { callback(null, []); return }
$.getJSON(jsonUrl, function(wordList) {
callback(null, wordList.map(function(ea) {
return {name: ea.word, value: ea.word, meta: "optional text"}
}));
})
}
}
langTools.addCompleter(rhymeCompleter);
Json file format :
[ {"word":"hello"},
{"word":"good morning"},
{"word":"suggestions"},
{"word":"auto suggest"},
{"word":"try this"}]
Reference/Demo :
http://plnkr.co/edit/6MVntVmXYUbjR0DI82Cr?p=preview
To add Live Auto Completion in Ace nowadays:
In your HTML include the ace/ext-language_tools.js.
The . call does not work well yet, so you may have to enter ctrl-space or alt-space for that, but standard syntax stuff such as writting function, will now show.
Then:
var editor = ace.edit("editor");
ace.require("ace/ext/language_tools");
editor.setOptions({
enableBasicAutocompletion: true,
enableSnippets: true,
enableLiveAutocompletion: true
});
The hard part of autocompletion is figuring out the keywords the rest is easy to do.
you need a popup, and listView to display completions, it might
be better to use Cocoa based popup.
some filtering function, simple startsWith check will do, but you can use nicer flex match
like sublime
trivial call to editor.session.replace to insert
selected completion
For 2-3 you should comment at https://github.com/ajaxorg/ace/issues/110 about your specific usecase since there is a work to get native support for AutoCompletion.

Hide (eSpeak) command prompt using Firefox

This is probably a stupid question. Firefox is rather rigid, as Internet Explorer is to be known to activate virusses without a problem.
But for my English classes I need eSpeak without the command screen. The program is run local, but I use HTML with javascript.
This is my code:
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
var localFile = Components.classes["#mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
var process = Components.classes["#mozilla.org/process/util;1"].createInstance(Components.interfaces.nsIProcess);
var args = new Array('-vmb-en1',"Say something");
localFile.initWithPath('C:\\WINDOWS\\espeak.exe');
process.init(localFile);
process.run(false, args, args.length);
I want to hide the prompt in Firefox.
Internet Explorer does what I want with:
try{var speak = new ActiveXObject('WScript.Shell');} catch(err){}
speak.Run('espeak -vmb-en1 "Say something"',0);
Any other suggestion to change the code is welcome.
I think your (and many other people) problem is this one : https://developer.mozilla.org/en-US/docs/Bypassing_Security_Restrictions_and_Signing_Code
But i don't know how to do now !!

Categories

Resources