Control a WebView object in Electron with typescript

坚强是说给别人听的谎言 提交于 2020-01-25 00:28:10

问题


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.



来源:https://stackoverflow.com/questions/53048143/control-a-webview-object-in-electron-with-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!