require.config({ paths: { 'vs': 'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.20.0/min/vs' }});
window.MonacoEnvironment = { getWorkerUrl: () => proxy };
let proxy = URL.createObjectURL(new Blob([`
self.MonacoEnvironment = {
baseUrl: 'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.20.0/min'
};
importScripts('https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.20.0/min/vs/base/worker/workerMain.min.js');
`], { type: 'text/javascript' }));
const
container = document.querySelector('#container'),
htmlContent = `
<body>
<div>Big brown fox jumps at lazy dog.</div>
<!-- I WANT TO ADD CODE HERE PROGRAMMATICALLY -->
<p>we have all the details for singleton methods.</p>
<div>new data comes here.</div>
</body>
`.trim(),
additionalHtmlContent = `
<div>
<strong>Hello World!</strong>
</div>
`.trim();
const computeInsertRange = (editor, pattern) => {
const lines = editor.getValue().split('\n');
for (let index = 0; index < lines.length; index++) {
if (lines[index].match(pattern)) {
const indent = /^\s*/.exec(lines[index])?.[0].length ?? 0;
return new monaco.Range(index + 1, indent + 1, index + 1, lines[index].length + 1);
}
}
return null;
};
// Adapted from: https://stackoverflow.com/a/48764277/1762224
const insertContent = (editor, pattern, content) => {
editor.executeEdits('my-source', [{
identifier: { major: 1, minor: 1 },
range: computeInsertRange(editor, pattern),
text: content,
forceMoveMarkers: true
}]);
};
require(['vs/editor/editor.main'], function () {
const editor = monaco.editor.create(container, {
value: htmlContent,
language: 'html',
theme: 'vs-dark'
});
setTimeout(() => {
insertContent(editor, /<!-- .+ -->/, additionalHtmlContent);
}, 1000);
});
html, body, #container {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
margin: 0;
padding: 0;
overflow: hidden;
}
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="94f9fbfaf5f7fbb9f1f0fde0fbe6d4a4baacbaa7">[email protected]</a>/min/vs/loader.js"></script>
<div id="container"></div>