淘寶站內(nèi)推廣方式有哪些班級優(yōu)化大師使用心得
頁面加載是 Web 組件的基本功能。根據(jù)頁面加載數(shù)據(jù)來源可以分為三種常用場景,包括加載網(wǎng)絡(luò)頁面、加載本地頁面、加載 HTML 格式的富文本數(shù)據(jù)。
頁面加載過程中,若涉及網(wǎng)絡(luò)資源獲取,需要配置ohos.permission.INTERNET網(wǎng)絡(luò)訪問權(quán)限。
加載網(wǎng)絡(luò)頁面
開發(fā)者可以在 Web 組件創(chuàng)建的時候指定默認加載的網(wǎng)絡(luò)頁面?。在默認頁面加載完成后,如果開發(fā)者需要變更此 Web 組件顯示的網(wǎng)絡(luò)頁面,可以通過調(diào)用loadUrl()接口加載指定網(wǎng)絡(luò)網(wǎng)頁。
在下面的示例中,在 Web 組件加載完“www.example.com”頁面后,開發(fā)者可通過 loadUrl 接口將此 Web 組件顯示頁面變更為“www.example1.com”。
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
webviewController: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('loadUrl')
.onClick(() => {
try {
// 點擊按鈕時,通過loadUrl,跳轉(zhuǎn)到www.example1.com
this.webviewController.loadUrl('www.example1.com');
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
// 組件創(chuàng)建時,加載www.example.com
Web({ src: 'www.example.com', controller: this.webviewController})
}
}
}
加載本地頁面
將本地頁面文件放在應用的 rawfile 目錄下,開發(fā)者可以在 Web 組件創(chuàng)建的時候指定默認加載的本地頁面?,并且加載完成后可通過調(diào)用loadUrl()接口變更當前 Web 組件的頁面。
在下面的示例中展示加載本地頁面文件的方法:
●?將資源文件放置在應用的 resources/rawfile 目錄下。圖 1?資源文件路徑

●?應用側(cè)代碼
//?xxx.ets
import?web_webview?from '@ohos.web.webview';
@Entry
@Component
struct?WebComponent?{
??webviewController:?web_webview.WebviewController?= new web_webview.WebviewController();
build() {
Column() {
Button('loadUrl')
.onClick(() => {
try {
//?點擊按鈕時,通過loadUrl,跳轉(zhuǎn)到local1.html
this.webviewController.loadUrl($rawfile("local1.html"));
} catch (error) {
console.error(`ErrorCode:?${error.code},??Message:?${error.message}`);
}
})
//?組件創(chuàng)建時,通過$rawfile加載本地文件local.html
Web({?src: $rawfile("local.html"),?controller: this.webviewController?})
}
}
}
●?local.html 頁面代碼。
<!--?local.html?-->
<!DOCTYPE?html>
<html>
<body>
<p>Hello?World</p>
</body>
</html>
加載 HTML 格式的文本數(shù)據(jù)
Web 組件可以通過loadData接口實現(xiàn)加載 HTML 格式的文本數(shù)據(jù)。當開發(fā)者不需要加載整個頁面,只需要顯示一些頁面片段時,可通過此功能來快速加載頁面。
//?xxx.ets
import?web_webview?from '@ohos.web.webview';
@Entry
@Component
struct?WebComponent?{
??controller:?web_webview.WebviewController?= new web_webview.WebviewController();
build() {
Column() {
Button('loadData')
.onClick(() => {
try {
//?點擊按鈕時,通過loadData,加載HTML格式的文本數(shù)據(jù)
this.controller.loadData(
'<html><body?bgcolor=\"white\">Source:<pre>source</pre></body></html>',
'text/html',
'UTF-8'
);
} catch (error) {
????????????console.error(`ErrorCode:?${error.code},??Message:?${error.message}`);
}
})
//?組件創(chuàng)建時,加載www.example.com
Web({?src: 'www.example.com',?controller: this.controller?})
}
}
}
點擊關(guān)注閱讀原文,了解更多資訊