window.customElements.define имеет значение null - не может создать Shadow DOM (в расширении Chrome) - PullRequest
1 голос
/ 15 апреля 2019

Я следую инструкции: https://alligator.io/web-components/composing-slots-named-slots/

Я следую совету: Как добавить разметку HTML через расширение Chrome, не пропуская стили страницы хоста в добавляемый элемент?

По какой-то причине возникает ошибка:

window.customElements.define('my-info-box', MyInfoBox);

myScript.js:82 Uncaught TypeError: Cannot read property 'define' of null

В зависимости от того, устанавливаю ли я точку останова, она ведет себя по-разному: https://en.wikipedia.org/wiki/Heisenbug

ДелатьВы случайно не знаете?

Я думал, что это могут быть проблемы с синхронизацией, поэтому попытался setTimeout, а также document.addEventListener('DOMContentLoaded', fireContentLoadedEvent); и сделать магию в обратном вызове ...




Объяснение видео: https://youtu.be/hpvRIlBtkEE

Код расширения

  let shadowDomMarkup = 
  `
    <my-info-box>
      <span slot="top">I'm in the shadow DOM injected by extension</span>
    </my-info-box>
  `;

  $(shadowDomMarkup).prependTo("body");

  (function() {
    const template = document.createElement('template');

    template.innerHTML = `
      <style>
        :host {
          display: block;
          background: red;
          border: 10px dashed black;
        }
      </style>

      <div>
        <slot name="top"></slot>
      </div>
    `;

    class MyInfoBox extends HTMLElement {
      constructor() {
        super();

        this.attachShadow({ mode: 'open' });
        this.shadowRoot.appendChild(template.content.cloneNode(true));
      }
    }

    window.customElements.define('my-info-box', MyInfoBox);

  })();

Грязный манифест (много экспериментов):

{
  "name": "Getting Started Example",
  "version": "1.0",
  "description": "Build an Extension!",
  "manifest_version": 2,
  "permissions": ["activeTab", "declarativeContent", "storage"],
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },

  "options_page": "options.html",
  "page_action": {
    "default_popup": "popup.html"
  },
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["zepto.min.js", "angular.js", "angular-route.js", "myScript.js"],
      "css": ["styles.css"],
      "run_at": "document_start"
    }
  ],
  "web_accessible_resources": [
    "iframed.html"
  ],
  "content_security_policy": "script-src 'self' https://ajax.googleapis.com; object-src 'self'"
}
...