简体   繁体   中英

Chrome (open) Shadow DOM Events Not Reaching Host

I'm running Chrome 56.0.x (corporate mandate), along with Polymer 2. My sample component isn't doing anything fancy; just raising a CustomEvent after making a simple AJAX call. I'm setting "bubbles":true and "composed":true, and I can validate that the event is dispatched and that my host is listening for the event properly.

sample-component.html

raiseDataRetrievedEvent() {
        this.dispatchEvent(
          new CustomEvent('sample-component-data-retrieved', {
            bubbles: true,
            composed: true,
            detail: { data: "loading complete" }
          }));
      }

However, the events never make it out of the Shadow DOM to my host page listeners.

index.html

// Listen to Custom event from Sample Component
  document.querySelector('sample-component').addEventListener('sample-component-data-retrieved', function (e) {
    alert(e.detail);
    console.log(e.detail);
  });

Interestingly enough, when I have a user initiated event (eg click) trigger this CustomEvent, it happily makes its way through the Shadow DOM to my listener. It's just the events that are programmatically created that are getting stuck.

UPDATE 1

This issue only seems to manifest itself when I'm serving my site locally (eg http://localhost , http://127.0.0.1 , http://COMPUTERNAME ). When I publish the site to another host, all the events seem to propagate as expected. Feels to me more like a Chrome issue at this point...

UPDATE 2

I put my code out on github here: https://github.com/davidfilkins/polymer-test .

I did some more testing and the results keep getting weirder... when I'm developing / testing in Chrome, I almost always have Dev Tools open. I noticed strangely enough that when my tools are open, that the event isn't captured by the host page (index.html)... but this seems to only happen locally. When I close tools and load the page locally, the events bubble properly... But this is only for the dispatched events that aren't tied to an explicit user action; those all seem to work regardless of the tools being open or not.

When I access the simple Azure app that I created - http://samplepolymertwo.azurewebsites.net/index.html - all events are bubbled / captured regardless of whether the tools are open.

No clue if this is fixed in more current versions of Chrome or not.

The culprit was all timing...

In Chrome, with Dev Tools open, running on localhost, the event was dispatched from the component before the event listener was wired up on the host page.

Event Timing

I suppose the ideal scenario would be for the web component to wait until the event listener on the host had been wired up before broadcasting the event.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM