1

In a Chrome Extension I'm injecting a content script into the page to create a widget of sorts.

I'm using a shadow DOM to avoid styles clashing. I can't figure out how to get the Javascript to fire in the below example:

content.js

//inject container div from Chrome Extension content script
var container = document.createElement('div');
container.setAttribute('id', 'myContainer');
container.setAttribute('style', 'all: initial');
document.body.appendChild(container);

//create shadow DOM within container
var theShadow = document.querySelector('#myContainer').attachShadow({mode: 'open'});

theShadow.innerHTML = `
    <div id="findMe">hello</div>
    <script>
        var a = document.querySelector("#findMe");
        console.log(a.innerHTML);
    </script>
`;
Xan
  • 74,770
  • 16
  • 179
  • 206
Jon
  • 452
  • 4
  • 23
  • `a.addEventListener('click', ()=>console.log(a.innerHTML));` may work (I'm on mobile and can't currently test), if you don't mind the requirement of clicking the element to trigger the logging. – David Thomas Dec 10 '18 at 12:06
  • @DavidThomas Unfortunately doesn't work. Even a simple `console.log` of a value doesn't work, seems the whole script is ignored – Jon Dec 10 '18 at 12:24
  • innerHTML does not run ` – wOxxOm Dec 10 '18 at 13:15
  • Further to @wOxxOm's comment, you'd need to use DOM node methods (demo 1: https://jsfiddle.net/davidThomas/Lnbdy85m/ demo 2: https://jsfiddle.net/davidThomas/Lnbdy85m/1/). Also, unfortunately, I have to close this question as a duplicate. – David Thomas Dec 10 '18 at 13:43
  • 1
    @DavidThomas No problem, thank you for your help – Jon Dec 10 '18 at 14:29

0 Answers0