my-component.js:24 Uncaught TypeError: window.open is not a function

my-component.js:24 Uncaught TypeError: window.open is not a function

我使用 vanilla js 创建了一个简单的 Web 组件,只需单击即可在新 window 上打开 URL 不幸的是,我收到以下错误

my-component.js:24 Uncaught TypeError: window.open is not a function

这是我的网络组件:

export class MyComponent extends HTMLElement {
  constructor() {
    super();
  }

  connectedCallback() {
    this._render();
    this._attachEventHandlers();
  }

  _render() {
    const container = document.createElement("div");
    container.innerHTML = `
            <div class='app'>
                <button id="open-me">Open</button>
          </div>`;

    const shadowRoot = this.attachShadow({ mode: "open" });
    shadowRoot.appendChild(container);
    }

    _attachEventHandlers() {
        this.shadowRoot.getElementById('open-me').addEventListener('click', () => {
            window.open('www.google.com', "_blank");
        })
    }
}

window.customElements.define("my-component", MyComponent);

这个组件的使用,只需导入你的HTML并像这样添加它

 <my-component></my-component>

这里有什么问题?

我会将其缩短为:

customElements.define("my-component", class extends HTMLElement {
  constructor() {
    let button = document.createElement("button");
    button.innerText = "open";
    button.onclick = (evt) => {
      alert("You clicked! " + evt.target.nodeName);
      open('www.google.com', "_blank");
    };
    super().attachShadow({mode:"open"})
           .append(button);
  }
});
<my-component></my-component>

  • 不需要命名 class 定义,当您只使用它一次时
  • 不需要 export,Web 组件是在全局注册表中创建的
  • 不需要 div 汤,除非它们确实有用途。
  • addEventListener 仅当您需要多个事件时才需要同一元素
  • window. 对于 customElementsalertopen 不需要;
    我们在浏览器中,默认是 window
  • super 设置 AND returns 'this' 范围;所以可以链接
  • attachShadow 集合 AND returns this.shadowRoot;所以可以链接
  • 了解 append 优于 appendChild
    的力量 https://developer.mozilla.org/en-US/docs/Web/API/Element/append

您的 open 问题不可能与 Web 组件有关;在控制台中检查原始语句。

在 Whosebug 中它说:

每个评论的后记

OP 负责覆盖 window.open 自己。