as

Settings
Sign out
Notifications
Alexa
亚马逊应用商店
AWS
文档
Support
Contact Us
My Cases
新手入门
设计和开发
应用发布
参考
支持

Vega WebView组件参考

Vega WebView组件参考

如果您希望进行设置以使用WebView,请参阅Vega网页应用概述

属性

source

使用可选标头加载给定的URI。source对象具有以下子属性

  • uri (string): 要在WebView上加载的URI。
  • headers (object): 随请求一起发送的其他HTTP标头。

示例如下。

已复制到剪贴板。

<WebView
    source ={{
        uri: "http://amazon.com/",
        headers: { "custom-app-header": "react-native-webview-app", "custom-app-header2": "VALEU2" }}}/>

onLoad

在WebView加载网页后,它会调用onLoad。示例如下。

已复制到剪贴板。

<WebView
  source={{ uri: 'https://amazon.com' }}
  onLoad={(event) => {
    console.log('url: ', event.nativeEvent.url)
  }}/>

使用以下属性引用onLoad函数:

已复制到剪贴板。

url(str) - WebView加载的URL
canGoBack(bool) - WebView追溯历史
canGoForward(bool) - WebView前进历史

onLoadStart

当WebView开始加载资源时,它会调用onLoadStart。示例如下。

已复制到剪贴板。

<WebView
  source={{ uri: 'https://amazon.com' }}
  onLoadStart={(event) => {
    console.log('url: ', event.nativeEvent.url)
  }}/>

使用以下属性引用onLoadStart

Copied to clipboard.

url(str) - WebView加载的URL
canGoBack(bool) - WebView追溯历史
canGoForward(bool) - WebView前进历史

onError

当WebView加载失败时,会调用onError

已复制到剪贴板。

示例如下。

<WebView
  source={{ uri: 'https://amazon.com' }}
  onError={(event) => {
    console.log('url: ', event.nativeEvent.url)
  }}/>

使用以下属性引用onError函数。

已复制到剪贴板。

url(str) - WebView加载的URL
canGoBack(bool) - WebView追溯历史
canGoForward(bool) - WebView前进历史
code(int)  - 错误代码
description(str) - 错误描述

onHttpError

当WebView加载失败导致此http状态错误时,会调用onHttpError函数。

任何statusCodes >= 400的情况都属于HTTP状态错误。

isMainFrame标记用于标识错误是在加载主页还是加载依赖资源时发生。对于主帧,此项将为true,对于子资源或iframe则为false

类型 必需
函数

示例如下。

已复制到剪贴板。

<WebView
  source={{ uri: 'https://example.com' }}
  onHttpError={(event) => {
    console.log('url: ', event.nativeEvent.url)
    console.log("HttpError statusCode, description, isMainFrame: ",
                  event.nativeEvent.statusCode,
                  event.nativeEvent.description,
                  event.nativeEvent.isMainFrame );
  }}/>

使用以下属性调用onHttpError函数:

已复制到剪贴板。

url
canGoBack
canGoForward
statusCode
description
isMainFrame

onCloseWindow

此函数通知载体应用关闭给定的WebView并将其从视图系统中删除。

由于此次调用之后的任何WebView交互都可能导致意外行为,因此载体应用应在收到此调用后销毁WebView实例。

此方法没有默认功能。

类型 必需
函数

示例如下。

已复制到剪贴板。

import React, { BackHandler } from 'react-native'; 
<WebView 
  source={{ uri : 'https://example.com/' }} 
  onCloseWindow={ 
    () => { // 处理加载的网页引发的关闭事件BackHandler.exitApp() }
   } />

onMessage

在WebView JS调用ReactNativeWebView.postMessage时引用。它接受一个参数并且可用于事件对象。数据必须是字符串。

示例如下。

已复制到剪贴板。

<WebView
  source={{ uri: 'https://amazon.com' }}
  onMessage={(event) => {
    console.log("data: ", event.nativeEvent.data);
  }}/>

onShouldStartLoadWithRequest

onShouldStartLoadWithRequest允许自定义任何WebView请求的处理。如果返回的值为true,则会继续加载请求,为false则停止加载。示例如下。

已复制到剪贴板。

<WebView
  source={{ uri: 'https://amazon.com' }}
  onShouldStartLoadWithRequest={(request) => {
        return request.url.startsWith('https://amazon.com');
  }}/>

onShouldStartLoadWithRequest对象可以包含以下属性。

Copied to clipboard.

url(str) - WebView加载的URL
canGoBack(bool) - WebView追溯历史
canGoForward(bool) - WebView前进历史
lockIdentifier(int) - JS原生同步锁定标识符号

onClientCertAuthentication(可选)

此可选函数让主应用能够管理客户端证书身份验证请求。

参数

  • 下面所示项为您提供身份验证请求的详细信息。

    已复制到剪贴板。

    request (Type: ClientCertAuthenticationRequest)
    
  • 这个回调对象有一个处理身份验证的函数。

    已复制到剪贴板。

    callback (Type: ClientCertAuthenticationCallback)
    

回调函数

  • 当证书采用PKCS#12格式时,下面的函数处理客户端证书身份验证。

    已复制到剪贴板。

      handleWithPkcs12(certificateData: Pkcs12CertificateData)
    
  • 下面的函数可取消客户端证书身份验证过程:

    已复制到剪贴板。

      cancel()
    

默认行为是在缺少客户端证书的情况下取消请求。

示例如下。

已复制到剪贴板。

<WebView
  source={{ uri: 'https://amazon.com' }}
  onClientCertAuthentication={(request, callback) => {

      // 要处理身份验证,可采用以下方式:
      callback.handleWithPkcs12({
            certificate: "base64-certificate",
            password: "certificate-password",
      });

      // 要拒绝请求,可采用以下方式:
      callback.cancel();
  }}/>

请求对象包含以下属性:

  • hostName - 服务器的主机名。
  • portNumber - 请求的端口号。

onSslError(可选)

此可选函数向主机应用程序通知在加载资源时出现了SSL错误。主机应用程序必须调用SslErrorHandler.cancel()SslErrorHandler.proceed()。默认情况下,如果加载URL时出现SSL错误,它会予以拒绝。

用户可以调用proceed()cancel() 方法来响应将来的SSL错误。默认情况下,会将资源加载过程取消。仅针对可修复的SSL证书错误(例如不可信的认证者、证书到期或自签名)调用此函数。对于不可修复的错误(例如服务器使客户端出现故障),WebView使用ERROR_FAILED_SSL_HANDSHAKE (-11) 参数调用onError(WebView, WebResourceRequest, WebResourceError)

示例如下。

已复制到剪贴板。

const handleSSLError = (sslError: SslErrorData , callback: OnSslErrorCallback) => {
    console.log("WebViewClient: ", sslError.url, sslError.code, sslError description);
    // 事先假设加载资源和用户选择可能需要一些时间,保持一定的延迟。
    setTimeout(() => {
    // 接受SSL错误。
    callback.proceed();
    // 拒绝SSL错误。
    // callback.cancel();
    }, 5000);
}
  <WebView
      source={{ uri: 'https://self-signed.badssl.com/' }}
      onSslError={(sslError: SslErrorData , callback: OnSslErrorCallback) => {
      HandleSSLError(sslError, sslErrorHandler);
  }}/>

SslErrorData对象

SslErrorData对象包含以下属性:

  • url
  • code
  • description

OnSslErrorCallback对象包含以下方法:

  • proceed() 允许SSL错误。
  • cancel() 拒绝SSL错误。

javaScriptEnabled

用于在WebView中启用或禁用JavaScript的布尔值。默认值为true

示例如下。

已复制到剪贴板。

<WebView
  source={{ uri: 'https://amazon.com' }}
  javaScriptEnabled={true}/>

domStorageEnabled

一个布尔值,用于在WebView中启用或禁用DOM存储(本地网页存储)。默认值为false

示例如下。

已复制到剪贴板。

<WebView
  source={{ uri: 'https://amazon.com' }}
  domStorageEnabled={true}/>

userAgent

为WebView设置user-Agent

示例如下。

已复制到剪贴板。

<WebView
  source={{ uri: 'https://amazon.com' }}
  userAgent={"custom-user-agent"}/>

mixedContentMode

为WebView指定混合内容模式。

示例如下。

已复制到剪贴板。

<WebView
  source={{ uri: 'https://amazon.com' }}
  mixedContentMode = {'always'}
  }/>

mixedContentMode的可能值如下。

  1. Never(默认):使用MIXED_CONTENT_NEVER_ALLOW。WebView不允许安全来源加载来自不安全来源的内容。我们推荐此模式,因为它最安全。
  2. Always:使用MIXED_CONTENT_ALWAYS_ALLOW。WebView允许安全来源从任何其他来源加载内容,即使该来源不安全。我们不建议使用此模式,因为它最不安全。
  3. Compatibility:使用MIXED_CONTENT_COMPATIBILITY_MODE。WebView尝试在混合内容方面兼容现代网页浏览器使用的方法。可能允许安全来源加载某些不安全的内容,而其他类型的内容将被阻止。允许或阻止的内容类型可能会随版本而有所不同,未明确定义。此模式适用于无法控制自己渲染的内容但需要一定合理安全性的应用。为了获得最高的安全性,请使用MIXED_CONTENT_NEVER_ALLOW

allowFileAccess

一个布尔值,用于允许或禁止使用file:// URI's访问文件系统。默认值为false

示例如下。

已复制到剪贴板。

<WebView
  source={{ uri: 'file:///<文件路径>' }}
  allowFileAccess = {true}/>

allowSystemKeyEvents

此布尔值决定应用程序是否在其Web JavaScript层中侦听特殊的系统按键事件,例如“后退”button(keyCode: 27)。此功能可帮助开发者将业务逻辑保留在网站上,而不必依赖适用于Vega的React Native应用程序代码。

当此属性为true时,系统会在网页JavaScript中传递按键事件,而不是在适用于Vega的React Native应用程序代码中。即使屏幕上显示了其他WebView实例,也只有最新的WebView实例才会接收系统按键事件。

示例如下。

已复制到剪贴板。

<WebView
  source={{ uri: 'https://amazon.com' }}
  allowSystemKeyEvents={true}/>

mediaPlaybackRequiresUserAction

一个布尔值,用于确定要开始播放HTML5音频和视频,是否需要用户做出手势。默认值为true

示例如下。

已复制到剪贴板。

<WebView
  source={{ uri: 'https://amazon.com' }}
  mediaPlaybackRequiresUserAction = {false}/>

thirdPartyCookiesEnabled

用于在WebView中启用或禁用第三方Cookie的布尔值。默认值为true,但将来会是false

示例如下。

已复制到剪贴板。

<WebView
  source={{ uri: 'https://amazon.com' }}
  thirdPartyCookiesEnabled={false}/>

allowsDefaultMediaControl

允许将VegaMediaControl事件自动桥接到活动的WebView媒体会话。这样就允许无缝集成WebView的语音命令。有关更多详细信息,请参阅Vega媒体控制概述

  • true时会启用WebView媒体会话的默认媒体传输控制,例如播放、暂停、向前查找、向后查找。
  • false时会禁用默认的媒体传输控制。

注意事项:

示例如下。

已复制到剪贴板。

<WebView
  source={{ uri: 'https://amazon.com' }}
  allowsDefaultMediaControl={true}/>

方法

injectJavaScript

injectJavaScript会在WebView中评估JavaScript。

示例如下。

已复制到剪贴板。

const webRef = useRef(null);
webRef.current.injectJavaScript('alert("Hello world")');

<WebView
  source={{ uri: 'https://amazon.com' }}
  ref={webRef}/>

stopLoading

这将停止加载当前页面。

示例如下。

已复制到剪贴板。

const webRef = useRef(null);
<WebView
  source={{ uri: 'https://amazon.com' }}
  onLoadStart={(event) => {
    webRef.current.stopLoading();
  }}
  ref={webRef}/>

clearCache(bool)

清除资源缓存。缓存是依据应用的,因此clearCache会清除同一应用的所有WebView部分的缓存。如果参数为true,则包括磁盘文件。如果参数为false,则仅清除RAM缓存。

示例如下。

已复制到剪贴板。

const webRef = useRef(null);

<WebView
  source={{ uri: 'https://amazon.com' }}
  ref={webRef}
  onLoad={(event) => {
    webRef.current.clearCache(true);
  }}/>

goBack()

在WebView历史记录中后退一页。如果历史记录中没有任何项目,此函数将不执行任何操作(无操作)并返回。

示例如下。

已复制到剪贴板。

const webRef = useRef(null);

<View style={{ flex: 1 }}>
  <Button
    title="GoBack"
    onPress={() => { if (webRef.current) { webRef.current.goBack(); }}}
  />
  <WebView
    source={{ uri: 'https://amazon.com' }}
    ref={webRef}
  />
</View>

goForward()

在WebView历史记录中向前移动一页。如果历史记录中没有任何可转发的项目,此函数将不执行任何操作(无操作)并返回。

示例如下。

已复制到剪贴板。

 const webRef = useRef(null);

 <View style={{ flex: 1 }}>
   <Button
     title="前进"
     onPress={() => { if (webRef.current) { webRef.current.goForward(); } }}
   />
   <WebView
     source={{ uri: 'https://example.com' }}
     ref={webRef}
   />
 </View>

clearHistory()

清除WebView实例的内部后退/前进历史记录。

示例如下。

已复制到剪贴板。

 const webRef = useRef(null);

 <View style={{ flex: 1 }}>
   <Button
     title="清除历史记录"
     onPress={() => { if (webRef.current) { webRef.current.clearHistory(); } }}
   />
   <WebView
     source={{ uri: 'https://example.com' }}
     ref={webRef}
   />
 </View>

dispatchTouchEvent(event: TouchEvent)

向指定的目标网页元素调度触摸事件。它让您能够以编程方式触发触摸事件,例如touchstarttouchend

参数

event: 表示调度的触摸的TouchEvent对象。此对象包含有关触摸事件类型 (type) 的信息以及与事件相关的触摸点数组(touches) 。

示例如下。

已复制到剪贴板。

  const webRef = useRef(null);

  <View style={{ flex: 1 }}>
    <Button
        title="触发触摸"
        onPress={() =>{
          const touches: Touch[] = [ { clientX: 100, clientY: 200 }];
          // 创建一个新的TouchEvent对象
          const touchStartEvent = new TouchEvent("touchstart", { touches });
          webRef.current && webRef.current.dispatchTouchEvent(touchStartEvent)
          // 创建一个新的TouchEvent对象
          const touchEndEvent = new TouchEvent("touchend", { touches });
          webRef.current && webRef.current.dispatchTouchEvent(touchEndEvent)}
        }
    />
    <WebView
      source={{ uri: 'https://amazon.com' }}
      ref={webRef}
    />
  </View>

scrollBy(offsetX: number, offsetY: number)

按指定的偏移值滚动WebView的内容。此方法让您能够以编程方式按指定的水平 (offsetX) 和垂直 (offsetY) 偏移量滚动WebView的内容。

参数

  • offsetX: 一个数字,表示滚动内容时的水平偏移量。为正值时向右滚动内容,为负值时向左滚动内容。
  • offsetY: 一个数字,表示滚动内容时的垂直偏移量。为正值时向下滚动内容,为负值时向上滚动内容。

示例如下。

已复制到剪贴板。

  const webRef = useRef(null);

  <View style={{ flex: 1 }}>
    <Button
      title="向下滚动"
      onPress={() => { if (webRef.current) { webRef.current.scrollBy(0, 100); } }}
    />
    <WebView
      source={{ uri: 'https://amazon.com' }}
      ref={webRef}
    />
  </View>

getVisualViewportInfo()

检索有关WebView视觉视口的信息。

返回值

一个对象,包含有关视觉视口的信息,包括:

  • height: 视觉视口的高度。
  • width: 视觉视口的宽度。
  • offsetTop: 从视觉视口顶部到内容顶部的偏移量。
  • offsetLeft: 从视觉视口左侧到内容左侧的偏移量。

示例如下。

已复制到剪贴板。

  const webRef = useRef(null);

  const handleWebViewLoad = (event: WebViewNavigationEvent) => {
      console.log(" getVisualViewportInfo: ", webRef.current.getVisualViewportInfo());
  };

  <View style={{ flex: 1 }}>
    <WebView
      source={{ uri: 'https://example.com' }}
      onLoad = {handleWebViewLoad}
      ref={webRef}
    />
  </View>

getContentSizeInfo()

检索有关WebView中内容大小的信息。

返回值

一个对象,包含有关内容大小的信息,包括:

  • scrollWidth: 内容的总宽度。
  • scrollHeight: 内容的总高度。

示例如下。

已复制到剪贴板。

  const webRef = useRef(null);

  const handleWebViewLoad = (event: WebViewNavigationEvent) => {
      console.log(" getContentSizeInfo: ", webRef.current.getContentSizeInfo());
  };

  <View style={{ flex: 1 }}>
    <WebView
      source={{ uri: 'https://example.com' }}
      onLoad = {handleWebViewLoad}
      ref={webRef}
    />
  </View>

reload()

此方法重新加载WebView实例的当前页面。

示例如下。

已复制到剪贴板。

 const webRef = useRef(null);

 <View style={{ flex: 1 }}>
  <Button
    title="重新加载"
    onPress={() => { if (webRef.current) { webRef.current.reload(); } }}
  />
  <WebView
    source={{ uri: 'https://example.com' }}
    ref={webRef}
  />
 </View>

Last updated: 2025年10月6日