This documentation is available as Markdown for AI agents and LLMs. See the full Markdown index or append .md to any documentation URL.
Expo WebBrowser
一个可访问系统 Web 浏览器并支持处理重定向的库。
expo-web-browser 提供访问系统 Web 浏览器的功能,并支持处理重定向。在 Android 上,它使用 ChromeCustomTabs,在 iOS 上,它使用 SFSafariViewController 或 ASWebAuthenticationSession,具体取决于你调用的方法。从 iOS 11 开始,SFSafariViewController 不再与 Safari 共享 Cookie,因此,如果你使用 WebBrowser 进行身份验证,应使用 WebBrowser.openAuthSessionAsync;如果你只是想打开网页(例如应用隐私政策),则使用 WebBrowser.openBrowserAsync
安装
If you are installing this in an existing React Native app, make sure to install expo in your project.
在应用配置中配置
如果你的项目中使用配置插件(Continuous Native Generation(CNG)),则可以使用内置的配置插件来配置 expo-web-browser。该插件允许你配置各种无法在运行时设置、需要构建新的应用二进制文件才能生效的属性。如果你的应用不使用 CNG,则需要手动配置此库
使用
处理来自 WebBrowser 的深层链接
如果你的项目使用 Expo Router,则会自动处理深层链接
如果你使用 WebBrowser 窗口进行身份验证,或用于其他需要通过深层链接将信息传回应用的场景,请在打开浏览器之前使用 Linking.addEventListener 添加处理程序。当监听器触发时,应调用 dismissBrowser。处理深层链接时,它不会自动关闭。除此之外,来自 WebBrowser 的重定向与其他深层链接的工作方式相同。请在 Linking 中阅读更多相关信息
API
import * as WebBrowser from 'expo-web-browser';
Methods
This methods removes all bindings to services created by warmUpAsync
or mayInitWithUrlAsync. You should call
this method once you don't need them to avoid potential memory leaks. However, those binding
would be cleared once your application is destroyed, which might be sufficient in most cases.
Promise<ServiceActionResult>The promise which fulfils with WebBrowserCoolDownResult when cooling is performed, or
an empty object when there was no connection to be dismissed.
Dismisses the current authentication session. On web, it will close the popup window associated with auth process.
voidThe void on the successful attempt or throws an error if dismiss functionality is not available.
Returns a list of applications package names supporting Custom Tabs, Custom Tabs
service, user chosen and preferred one. This may not be fully reliable, since it uses
PackageManager.getResolvingActivities under the hood. (For example, some browsers might not be
present in browserPackages list once another browser is set to default.)
Promise<WebBrowserCustomTabsResults>The promise which fulfils with WebBrowserCustomTabsResults object.
Possibly completes an authentication session on web in a window popup. The method should be invoked on the page that the window redirects to.
Returns an object with message about why the redirect failed or succeeded:
If type is set to failed, the reason depends on the message:
Not supported on this platform: If the platform doesn't support this method (Android, iOS).Cannot use expo-web-browser in a non-browser environment: If the code was executed in an SSR or node environment.No auth session is currently in progress: (the cached state wasn't found in local storage). This can happen if the window redirects to an origin (website) that is different to the initial website origin. If this happens in development, it may be because the auth started on localhost and finished on your computer port (Ex:128.0.0.*). This is controlled by theredirectUrlandreturnUrl.Current URL "<URL>" and original redirect URL "<URL>" do not match: This can occur when the redirect URL doesn't match what was initial defined as thereturnUrl. You can skip this test in development by passing{ skipRedirectCheck: true }to the function.
If type is set to success, the parent window will attempt to close the child window immediately.
If the error ERR_WEB_BROWSER_REDIRECT was thrown, it may mean that the parent window was
reloaded before the auth was completed. In this case you'll need to close the child window manually.
This method initiates (if needed) CustomTabsSession
and calls its mayLaunchUrl method for browser specified by the package.
Promise<ServiceActionResult>A promise which fulfils with WebBrowserMayInitWithUrlResult object.
On Android:
This will be done using a "custom Chrome tabs" browser, AppState, and Linking APIs.
On iOS:
Opens the url with Safari in a modal using ASWebAuthenticationSession. The user will be asked
whether to allow the app to authenticate using the given url.
To handle redirection back to the mobile application, the redirect URI set in the authentication server
has to use the protocol provided as the scheme in app.json expo.scheme.
For example, demo:// not https:// protocol.
Using Linking.addEventListener is not needed and can have side effects.
On web:
This API can only be used in a secure environment (localhost/https). to test this. Otherwise, an error with code
ERR_WEB_BROWSER_CRYPTOwill be thrown. This will use the browser'swindow.open()API.
- Desktop: This will create a new web popup window in the browser that can be closed later using
WebBrowser.maybeCompleteAuthSession(). - Mobile: This will open a new tab in the browser which can be closed using
WebBrowser.maybeCompleteAuthSession().
How this works on web:
- A crypto state will be created for verifying the redirect.
- This means you need to run with
npx expo start --https
- This means you need to run with
- The state will be added to the window's
localstorage. This ensures that auth cannot complete unless it's done from a page running with the same origin as it was started. Ex: ifopenAuthSessionAsyncis invoked onhttps://localhost:19006, thenmaybeCompleteAuthSessionmust be invoked on a page hosted from the originhttps://localhost:19006. Using a different website, or even a different host likehttps://128.0.0.*:19006for example will not work. - A timer will be started to check for every 1000 milliseconds (1 second) to detect if the window
has been closed by the user. If this happens then a promise will resolve with
{ type: 'dismiss' }.
On mobile web, Chrome and Safari will block any call to
window.open()which takes too long to fire after a user interaction. This method must be invoked immediately after a user interaction. If the event is blocked, an error with codeERR_WEB_BROWSER_BLOCKEDwill be thrown.
Promise<WebBrowserAuthSessionResult>- If the user does not permit the application to authenticate with the given url, the Promise fulfills with
{ type: 'cancel' }object. - If the user closed the web browser, the Promise fulfills with
{ type: 'cancel' }object. - If the browser is closed using
dismissBrowser, the Promise fulfills with{ type: 'dismiss' }object.
Opens the url with Safari in a modal on iOS using SFSafariViewController,
and Chrome in a new custom tab
on Android. On iOS, the modal Safari will not share cookies with the system Safari. If you need
this, use openAuthSessionAsync.
Promise<WebBrowserResult>The promise behaves differently based on the platform.
On Android promise resolves with { type: 'opened' } if we were able to open browser.
On iOS:
- If the user closed the web browser, the Promise resolves with
{ type: 'cancel' }. - If the browser is closed using
dismissBrowser, the Promise resolves with{ type: 'dismiss' }.
This method calls the warmUp method on CustomTabsClient
for specified package.
Promise<ServiceActionResult>A promise which fulfils with WebBrowserWarmUpResult object.
Types
If there is no native AuthSession implementation available (which is the case on Android) the params inherited from
WebBrowserOpenOptions will be used in the browser polyfill. Otherwise, the browser parameters will be ignored.
Type: WebBrowserOpenOptions extended by:
Literal type: union
Acceptable values are: WebBrowserRedirectResult | WebBrowserResult
Enums
A browser presentation style. Its values are directly mapped to the UIModalPresentationStyle.
WebBrowserPresentationStyle.AUTOMATIC = "automatic"The default presentation style chosen by the system.
On older iOS versions, falls back to WebBrowserPresentationStyle.FullScreen.
WebBrowserPresentationStyle.CURRENT_CONTEXT = "currentContext"A presentation style where the browser is displayed over the app's content.
WebBrowserPresentationStyle.FORM_SHEET = "formSheet"A presentation style that displays the browser centered in the screen.
WebBrowserPresentationStyle.FULL_SCREEN = "fullScreen"A presentation style in which the presented browser covers the screen.
WebBrowserPresentationStyle.OVER_CURRENT_CONTEXT = "overCurrentContext"A presentation style where the browser is displayed over the app's content.
WebBrowserPresentationStyle.OVER_FULL_SCREEN = "overFullScreen"A presentation style in which the browser view covers the screen.
WebBrowserPresentationStyle.PAGE_SHEET = "pageSheet"A presentation style that partially covers the underlying content.
错误代码
ERR_WEB_BROWSER_REDIRECT
**仅限 Web:**窗口无法完成重定向请求,因为调用窗口没有指向其父窗口的引用。如果父窗口被重新加载,可能会发生这种情况
ERR_WEB_BROWSER_BLOCKED
**仅限 Web:**弹出窗口被浏览器阻止或未能打开。当 window.open() 方法在用户输入触发后经过太长时间才被调用时,移动浏览器中可能会发生这种情况
移动浏览器这样做是为了防止恶意网站在移动设备上打开大量不需要的弹出窗口
你的方法仍然可以在异步函数中运行,但在此之前不能有任何长时间运行的任务。你可以使用钩子,在其他进程完成加载之前禁用用户输入
ERR_WEB_BROWSER_CRYPTO
**仅限 Web:**当前环境不支持加密功能。请确保你是在安全来源(localhost/https)中运行的。