My goal here is to insert an image in Quill editor in react-native-webview component as shown below. For which I need access to the quill variable in the script tag:
<WebView
originWhitelist={['*']}
ref={(r) => setWebref(r)}
javaScriptEnabled={true}
source={{
html: `<head>
<link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">
<script src="https://cdn.quilljs.com/1.3.6/quill.js"></script>
</head>
<body>
<div id="editor" >${content}</div>
</body>
<script>
var toolbarOptions = [[ 'bold', 'italic',],];
var quill = new Quill('#editor', {
modules: {
toolbar: toolbarOptions
})
</script>`,
}}
/>
When I try to run following snippet outside webview in react-native, nothing is happening
const url = `https://...`;
const code = `const range = window.quill.getSelection();
window.quill.insertEmbed(range.index, 'image', ${url});
`;
webref.injectJavaScript(code);
But, when I try to run following snippet outside webview in react-native, I am getting the expected result.
const snippet = `document.body.style.backgroundColor = 'blue';
true;
`;
webref.injectJavaScript(snippet);
Problem lies in
const url = `https://...`;
const code = `const range = window.quill.getSelection();
window.quill.insertEmbed(range.index, 'image', ${url});
`;
when you have const url = `https://blah.com`;
and const code = `....insertEmbed(range.index, 'image', ${url});`;
, the net result of the injected code would be ...insertEmbed(range.index, 'image', https://blah.com);
, which in the eyes of a JavaScript engine is a syntax error. These backtick demarcated strings are known as template string literals, which are used for formatting strings. So, for your code block to work, it should be corrected as follows.
const url = `https://...`;
const code = `const range = window.quill.getSelection();
window.quill.insertEmbed(range.index, 'image', '${url}');
`; //NOTICE THE SINGLE QUOTES AROUND ${url}