Chrome 是否可以从外部脚本将事件侦听器绑定到影子dom中的元素?

dtcbnfnu  于 12个月前  发布在  Go
关注(0)|答案(3)|浏览(92)

我有一个Chrome扩展,它在页面中注入了一个shadow dom元素来保持css的独立性。但是我需要从内容脚本中将onclick绑定到shadow dom中的一些元素,因为我需要能够通过单击shadow dom中的元素来调用内容脚本中的函数。
我尝试在模板元素和实际的shadow dom元素上使用.bind('click',function(){}),但似乎无法访问它们。这可能吗?

yzuktlbb

yzuktlbb1#

尝试查询元素的shadowRoot。换句话说,假设你有一个元素<super-ultra-element>,在该元素的shadow dom中有一个div,类为'potato',你希望附加一个click处理程序。
您应该能够通过首先获取元素的shadowRoot来完成此操作:var superUltraRoot = document.querySelector('super-ultra-element').shadowRoot;
一旦你有了shadowRoot,你就可以查询元素的shadow dom来找到你关心的项目:var potatoDiv = superUltraRoot.querySelector('.potato');
现在,您已经有了一个对要添加click处理程序的元素的引用,所以这样做应该相当容易:potatoDiv.addEventListener('click', someClickCallback);

ruarlubt

ruarlubt2#

我尝试在template元素中的两个元素上使用.bind('click',function(){})
1.将事件侦听器添加到模板不起作用。你绑定的元素应该是DOM的一部分。
和实际的shadow dom元素,但我似乎无法访问它们
1.我不认为jquery理解shadow-root。如果你使用jquery来查询shadow-dom中的元素,我不认为它会返回一个节点(应该吗?)
所以,你有两个选择:
1.正如其他答案中所建议的,您可以通过在shadow-root中查询它来将eventlistener绑定到实际元素,这可以通过元素上的shadowRoot属性访问。
1.或者,您可以使用jquery event-delegation将事件侦听器绑定到具有适当选择器的父节点(在本例中为shadow-dom的host)上。当事件将传播到父级时,将触发侦听器。
例如:

$( "#list" ).on( "click", "a", function( event ) {
    event.preventDefault();
    console.log( $( this ).text() );
});
anauzrmj

anauzrmj3#

我正在使用Jquery findon函数的替代方法,在这里尝试我的片段。

$("#CreateShadowRoot").on('click', function (event) {
    const shadowDiv = document.getElementById('ShadowDiv');
    const shadowRoot = shadowDiv.attachShadow({ mode: 'open' });
    const jQueryScript = document.createElement('script');
    jQueryScript.src = 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js'; 
    shadowRoot.appendChild(jQueryScript);
    shadowRoot.innerHTML += '<button id="example-action">Im inside ShadowRoot</button>';
    function initShadowDOM() {
      // Get the Shadow DOM root element
      // Attach a click event listener using jQuery
      $(shadowRoot).find("#example-action").on('click', function (event) {
        // Handle the click event within the Shadow DOM
        // You can access the event object and perform actions here
        console.log('Event received');
      });
    }
    jQueryScript.onload = function () {
      // jQuery is now loaded and ready to use
      // You can use jQuery event listeners like .on() here
      initShadowDOM(); // Call a function to set up the Shadow DOM content and event listeners
    };
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="CreateShadowRoot">Create ShadowRoot</button>
<div id="ShadowDiv"></div>

相关问题