window.customElements.define为null-无法创建Shadow DOM(在Chrome扩展程序中)

时间:2019-04-15 07:26:01

标签: google-chrome google-chrome-extension shadow-dom custom-element

我正在学习本教程:https://alligator.io/web-components/composing-slots-named-slots/

我正在遵循建议:How to append a HTML markup via Chrome Extension without leaking styles of the host page to the appended element?

由于某种原因出现错误:

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

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

取决于我是否设置断点,其行为会有所不同:https://en.wikipedia.org/wiki/Heisenbug

您碰巧知道吗?

我认为这可能是计时问题,因此我们尝试了setTimeoutdocument.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'"
}

0 个答案:

没有答案