Control a WebView object in Electron with typescri

2019-08-10 05:20发布

问题:

I'm trying to generate a instance of a webview using typescript.

I'm using electron-forge's react-typescript template.

I tried the following:

import {Component} from 'react';
import * as React from 'react';
import {WebviewTag} from 'electron';

class MediaWebView extends Component<{ url: string }, {}> {

  renderWebVierw() {
    const myWebView: WebviewTag /* error here */ =
      (<webview src={this.props.url}
                autosize='on'
                nodeintegration='on'
                disablewebsecurity='on'
                webpreferences='allowRunningInsecureContent'
                style={webViewStyle}
      />);
    return myWebView;
  }

This renders the webview but throws the following error: TS2322: Type 'Element' is not assignable to type 'WebviewTag'. Property 'addEventListener' is missing in type 'Element'.

I can't suscribe to events or inject code into the webview.

I don't know what type should I be assigning, but I can't seem to find it.

What's the correct way to implement a webview, and have access to its methods using typescript?

回答1:

const webview: WebViewTag = (<webview />) as WebViewTag;

Had the same problem. The issue is because without the as, the compiler doesn't know that what you're doing is returning a WebViewTag object, and the left-hind side of the equation doesn't care because WebViewTag inherits from HtmlElement. In this case as SomeClass will coerce the object into whatever type you try to cast it to, and if the types match, then it will return the object, if they don't, it will just return null.