0

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.

enter image description here

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.

enter image description here

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.

enter image description here

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.

enter image description here

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()?

Khalid Farhan
  • 435
  • 1
  • 3
  • 19
  • 1
    ManifestV3 extensions can't inject literal code in the content script, see the workarounds in [this answer](/a/9517879). However, note that such code cannot be called from content script due to isolation as explained in the answer I've linked. If you need further assistance please clarify the goal of your extension and why you inject the code. – wOxxOm Jun 18 '23 at 08:59
  • @wOxxOm Thanks. I need all data of console.log. This solution works fine. https://stackoverflow.com/questions/19846078/how-to-read-from-chromes-console-in-javascript/19846113#19846113 I get the console.log data only which are in `content_scripts.js`. Suppose when the extension runs above of example.com I need the console.log of the example.com – Khalid Farhan Jun 18 '23 at 10:28

0 Answers0