For developing a Chrome extension, I am injecting JS code from content_scripts into the site. content_scripts.js
code looks like:
const mainDiv = document.createElement('div');
mainDiv.innerHTML =
`<div id="innerDiv">Lorem ipsum</div>
<script>
alert("First");
function doSome(){
alert("Hi");
}
</script>`;
document.body.insertAdjacentElement('beforeend', mainDiv);
setTimeout(() => {
alert("Test");
doSome();
}, 5000);
In the website HTML
tag and JavaScript
were injected.
doSome()
function and alert("First")
not executing. But this alert("Test")
is executing.
The browser console gives an error message content_scripts.js:1 Uncaught ReferenceError: doSome is not defined
.
I've also tried it in a different way. content_scripts.js
code looks like:
const mainDiv = document.createElement('div');
mainDiv.innerHTML =
`<div id="innerDiv">Lorem ipsum</div>`;
document.body.insertAdjacentElement('beforeend', mainDiv);
document.getElementById('innerDiv').innerHTML =
`<script>
alert("Second");
function doAnother(){
alert("Hello");
}
</script>`;
setTimeout(() => {
alert("Best");
doAnother();
}, 5000);
In the website HTML
tag and JavaScript
were injected.
doAnother()
function and alert("Second")
not executing. But this alert("Best")
is executing.
The browser console gives an error message content_scripts.js:1 Uncaught ReferenceError: doAnother is not defined
.
It was flagged as a duplicate. I also tried eval()
but no luck.
What can I do to execute alert("First")
or alert("Second")
or doSome()
or doAnother()
?