Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to bind an event listener to an element within a shadow dom from external script?

I have a chrome extension that injects a shadow dom element to a page to keep the css separate. But I need to bind an onclick to some elements within the shadow dom from a content script because I need to be able to invoke functions in the content script by clicking on the elements that are in the shadow dom.

I have tried using the .bind('click', function(){}) on both the elements in the template element and the actual shadow dom element but I can't seem to access them. Is this possible?

like image 608
Shawn Volpe Avatar asked Dec 05 '15 23:12

Shawn Volpe


People also ask

Can we use JS DOM to add event listeners to elements?

You can add event listeners to any DOM object not only HTML elements. i.e the window object. The addEventListener() method makes it easier to control how the event reacts to bubbling.

How do you access the elements inside shadow DOM?

We can only access the shadow DOM by the reference returned by attachShadow (and probably hidden inside a class). Browser-native shadow trees, such as <input type="range"> , are closed.

How do you handle shadow DOM elements?

To access these Shadow DOM elements, we need to use the JavascriptExecutor executeScript() function. If you look at the DOM structure, every element that includes Shadow DOM also has a shadowRoot property that describes the underlying elements.


1 Answers

Try querying against the element's shadowRoot. In other words, lets say you have an element <super-ultra-element>, and inside that element's shadow dom is a div with class 'potato' that you wish to attach a click handler to.

You should be able to do this by first obtaining the element's shadowRoot: var superUltraRoot = document.querySelector('super-ultra-element').shadowRoot;.

Once you have the shadowRoot, you can query the element's shadow dom for the item you care about: var potatoDiv = superUltraRoot.querySelector('.potato');.

You now have a reference to the element you're trying to add a click handler to, so doing so should be fairly easy: potatoDiv.addEventListener('click', someClickCallback);

like image 110
Dogs Avatar answered Oct 24 '22 20:10

Dogs