When an operation is performed on other pages of the mini program, the data changes. When returning to the webview page, the data in the webview needs to be updated. Since the mini program does not provide real-time communication capabilities with the webview, refreshing the page is a consideration.
The most common method is to modify the url of the webview, add some query parameters or something, and the page will be updated. However, this will increase the browsing history of the webview, causing the user to return to the previous page in the webview instead of the previous page of the applet when going back.
Call the wx.redirectTo(OBJECT)
method in the applet. Fill in the url of the current page here. In fact, closing the current page and reopening it achieves the purpose of refreshing the webview in disguise. However, since the mini program page is reopened, it will take longer. Also, the user will see the previous page flash, and then the new page will appear.
First, let the webview do conditional rendering:
<web-view wx:if="{{ webviewUrl }}" src="{{ webviewUrl }}" />
When you need to refresh, first set the webviewUrl to empty and destroy the current webview. Then set webviewUrl to the current value. As follows:
refreshWebview: function () { let tmpUrl = this.data.webviewUrl; this.setData({ webviewUrl: '' }); setTimeout(() => { this.setData({ webviewUrl: tmpUrl }) }, 100); }
In this way, the page can be refreshed without affecting the navigation bar history, or it can be a jump url.
After setData here, the update of the page content should be executed asynchronously, so we need to delay for a short period of time when we modify the url, otherwise an error will occur.
I guess that the actual update of the page after setData should be in the next requestAnimationFrame, so if the page is not stuck at all, it may be 16ms. To be on the safe side, I set it to 100ms.
From what I have learned so far, there is indeed no simple API that can directly refresh the mini program webview without side effects. Method three is a method I figured out myself. But I always feel that such a simple problem should have a more direct approach, which is strange.
Related articles:
JS refresh parent window Summary of several methods
The above is the detailed content of Three methods for updating webview pages in WeChat applet. For more information, please follow other related articles on the PHP Chinese website!