[英]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. 我有一个chrome扩展,它将一个阴影dom元素注入页面以保持css分离。 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.
但是我需要将onclick绑定到内容脚本中的阴影dom中的一些元素,因为我需要能够通过单击阴影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. 我已经尝试在模板元素中的元素和实际的阴影dom元素上使用.bind('click',function(){}),但我似乎无法访问它们。 Is this possible?
这可能吗?
Try querying against the element's shadowRoot. 尝试查询元素的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. 换句话说,假设你有一个元素
<super-ultra-element>
,并且在该元素的阴影dom内部是一个带有'马铃薯'类的div,你希望附加一个点击处理程序。
You should be able to do this by first obtaining the element's shadowRoot: var superUltraRoot = document.querySelector('super-ultra-element').shadowRoot;
你应该能够通过首先获得元素的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');
拥有shadowRoot后,您可以查询元素的阴影dom以查找您关注的项目:
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);
您现在可以引用您尝试添加单击处理程序的元素,因此这样做应该相当简单:
potatoDiv.addEventListener('click', someClickCallback);
I have tried using the .bind('click', function(){}) on both the elements in the template element
我已经尝试在模板元素中的两个元素上使用.bind('click',function(){})
and the actual shadow dom element but I can't seem to access them
和实际的影子dom元素,但我似乎无法访问它们
So, you have 2 options: 所以,你有两个选择:
Ex: 例如:
$( "#list" ).on( "click", "a", function( event ) {
event.preventDefault();
console.log( $( this ).text() );
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.