I'm working on an application which needs to insert text into a contenteditable="true" div (a Draftjs based textfield to be precise).
Now I am aware that Draft.js uses react and that it should be used that way, but in this case, the application already exists and this is a third party electron app that works with it.
I'm working on in-line notification replying on macOS, so I need that reply text to be pasted inside the draftJS field, however, when I do so using:
document.querySelector('div[contenteditable="true"]').focus();
document.execCommand('insertText', false, 'message');
It throws an error:
I was able to make it work using:
const event = document.createEvent('TextEvent');
event.initTextEvent('textInput', true, true, window, 'message', 0, locale);
but this API is deprecated and doesn't work properly if the message contains an emoji.
Is there any way to do this that doesn't cause an error?
I found out that the new API that is supposed to replace initTextEvent is just new Event() (see docs), but I can't find out if it supports textInput events.
To play around with it you can just go to https://draftjs.org/ and play with it in chrome dev tools.
I would really appreciate some help here as I don't know what to do to make it work anymore. Also, I know people are a fan of jquery, but I'd prefer a native js solution (although any solution is welcome).
edit:
Please note:
I'm not using react, the input field I want to modify (draftjs) is using react and I want to input text into it using native js.
edit 2:
For anyone else coming across this issue, I wanted to insert text into the Facebook messenger text field (which uses Draftjs).
I managed to find a working workaround.
It does use the deprecated API (event.initTextEvent), but it's the only way that I've found that works, even with emoji. Please do post an answer if you have a better solution to this.
It works like this:
async function sendReply(message: string): Promise<void> {
const inputField = document.querySelector('[contenteditable="true"]') as HTMLElement;
if (inputField) {
const previousMessage = inputField.textContent;
// Send message
inputField.focus();
await insertMessageText(message, inputField);
(await elementReady('._30yy._38lh._39bl')).click();
// Restore (possible) previous message
if (previousMessage) {
insertMessageText(previousMessage, inputField);
}
}
}
function insertMessageText(text: string, inputField: HTMLElement): void {
// Workaround: insert placeholder value to get execCommand working
if (!inputField.textContent) {
const event = document.createEvent('TextEvent');
event.initTextEvent('textInput', true, true, window, '_', 0, '');
inputField.dispatchEvent(event);
}
document.execCommand('selectAll', false, undefined);
document.execCommand('insertText', false, text);
}
This is typescript code, so you might want to change it up to use js.
It works by inserting a placeholder value inside the textField using event.initTextEvent, and then replacing that text with:
document.execCommand('selectAll', false, undefined);
document.execCommand('insertText', false, 'text');
tested in Chrome: Version 71.0.3578.98
Although the question was asked a long ago and #JoniVR found a workaround, this may help someone else.
I was also having a similar problem while working on an extension. I also tried the method document.execCommand('insertText', false, text). It worked on LinkedIn but not on Facebook. It was inserting text in the wrong node. Although document.execCommand API works in some places, it's obsolete now.
For Facebook and any other sites using drafjs editor, We need to dispatch a paste event using dataTransfer and clipBoardEvent APIs to make draftjs think that the text is pasted and process accordingly.
const dataTransfer = new DataTransfer();
function dispatchPaste(target, text) {
// this may be 'text/html' if it's required
dataTransfer.setData('text/plain', text);
target.dispatchEvent(
new ClipboardEvent('paste', {
clipboardData: dataTransfer,
// need these for the event to reach Draft paste handler
bubbles: true,
cancelable: true
})
);
// clear DataTransfer Data
dataTransfer.clearData();
}
Check this link in case more info needed.
Related
I'm having difficulties to add an HyperLink to my Word Document using the Javascript API. I've look to Doc and I can't find any hints how to accomplish my duty...
Here is my Question: What is the best way to add an HyperLink inside a Word Document using the Javascript API.
And Here is what I tried:
Word.run((context: Word.RequestContext) => {
var range = context.document.getSelection();
context.load(range, "hyperlink");
return context.sync().then(() => {
range.font.highlightColor = '#FFFF00';
range.hyperlink = "C:\My Documents\MyFile.doc";
}).then(context.sync);
});
I've added the highlightColor just to have a visual that my changes are being sync. Everything seems fine but the Hyperlink property is not being updated. Am I missing something?
And If you guys are wondering what's this syntax, I'm using TypeScript.
Good, if you don't mind i will reply in JavaScript :)
Setting a hyperlink to a file must work (provided that the file exists :) ). I have this simplified example working successfully, btw you don't need to load the range for setting this.
Also hyperlinks is now supported as preview, so please make sure that you are running an updated (latest) version of Word (go file and install updates) and most importantly make sure you are using the preview CDN for Office.js which is here: https://appsforoffice.microsoft.com/lib/beta/hosted/office.js
Word.run(function(context) {
// Insert your code here. For example:
context.document.getSelection().hyperlink = "C:\My Documents\MyFile.doc";
return context.sync();
});
I've forked a Gnome Shell Extension, as I want to modify it to fit my personal preferences. I want to send a notification each time an event occurs. Sending the notification itself is fairly easy with Main.notify(summary, text). However, I just can't find out how to set a custom icon. [EDIT: The following is wrong. I looked up bad code]According to the github repo of gnome-shell I can define an icon via an optional parameter: Main.notify(summary, text, params), where params will be checked in MessageTray.js l.367:
params = Params.parse(params, { gicon: null,
secondaryGIcon: null,
bannerMarkup: false,
clear: false,
soundName: null,
soundFile: null });
if (params.gicon || params.clear)
this.gicon = params.gicon;
So I tried to use the following command:
Main.notify(summary, text, {gicon: myicon});
But the {gicon: myicon} part is ignored completely and the default icon is used :-/.
I'm new to Javascript and GNOME programming, so pls don't hate me :-)
Is using Main.notify() recommended generally, or is it deprecated?
Cheers, Maphardam
I think that Main.notify() is generally recommended, as it is used in some of the "official" extensions.
However, Main.notify() only takes two parameters (msg, details) and thus you cannot use this function to set a custom icon.
You can however copy the source of Main.notify() and adapt it to your own needs. Inside the following function the source of the notification is set to a newly created source with a custom icon.
function notify(msg, details, icon) {
let source = new MessageTray.Source("MyApp Information", icon);
Main.messageTray.add(source);
let notification = new MessageTray.Notification(source, msg, details);
notification.setTransient(true);
source.notify(notification);
}
For example you could call it with notify("MyApp", "Test", 'folder-symbolic');.
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");
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.
I have just implemented TinyMCE and it is working fine, except that the user must type something, even a space character, before being able to delete content.
Please tell me if you need more information.
It's a browser bug. There is a hacky workaround I've seen and used in the past; I can't verify it at the moment. If you call the following once the TinyMCE editing iframe has loaded, it may work:
// doc is a reference to the iframe's document
try {
doc.execCommand("Undo", false, false);
} catch (ex) {}
Indeed it is a browser bug (almost FF). My workaround for this resets the design mode:
editor_instance = tinymce.EditorManager.getInstanceById(editor_id); //editor id needed here (ed.id)
editor_instance.getDoc().designMode = 'Off';
editor_instance.getDoc().designMode = 'On';