I was trying to implement the Monaco editor on a web project using parcel as a bundler, but find it quite difficult to prevent a paste action (I do not want the users to paste codes in the editor).
This was how I initialised the editor
import * as monaco from 'monaco-editor/esm/vs/editor/editor.main.js';
// set monaco web workers url
window.MonacoEnvironment = {
getWorkerUrl: (moduleId, label)=> {
if (label === 'json') {
return '../language/json/json.worker.js';
}
if (label === 'css') {
return '../language/css/css.worker.js';
}
if (label === 'html') {
return '../language/html/html.worker.js';
}
if (label === 'typescript' || label === 'javascript') {
return '../language/typescript/ts.worker.js';
}
return '../editor/editor.worker.js';
}
};
export const monacoCreate = (MonacoConfig = {}, doc) => monaco.editor.create(doc, {
value: [
'function x() {',
'\tconsole.log("Hello world!");',
'}'
].join('\n'),
language: "javascript",
theme: "white",
mouseWheelZoom: true,
readOnly: false,
showUnused: true,
wordWrap: "on",
selectionClipboard: false,
...MonacoConfig
});
This was how I created an instance of the editor in a div
with id code
const select = document.querySelector.bind(document);
const editor = monacoCreate({ language: language.html }, select('#code'));
The challenge now is on reading the Monaco docs
, I can't find an inbuilt method to prevent a paste event in the editor, neither have I found a walk around it. Please help.
Found a workaround this.
Monaco has an inbuilt onKeyDown()
method that returns an event(Details about the keys pressed and keys not pressed).
All I did was to get the keyCode
of the key pressed and also check if the CTRL
or CMD
key has been pressed
Hence, on pasting an item to the Monaco editor, I prevent the default action when CtrlOrCmd+v
and CtrlOrCmd+c
keys are pressed.
below shows how I implemented the fix
editor.onKeyDown((event)=>{
const {keyCode, ctrlKey, metaKey} = event;
if((keyCode === 33 || keyCode ===52) && (metaKey || ctrlKey)){
event.preventDefault();
}
});