这里是web组件初始化的代码
WebComponent({ webScrollBottom: this.webScrollToBottom, messageHandler: this.messageHandler ,contentString:this.detailModel!.html
,webHeight:this.webHeight
,timeCellSrollDisMiss:this.timeCellScrollDismiss
,relatedCellScrollDisMiss:this.relatedScrollDismiss,
draggingWeb:this.draggingWeb,
webScrollTop:this.webScrollTop})
```
这里是web组件的代码
export struct WebComponent {
@Prop webHeight: number = 0;
@Link timeCellSrollDisMiss: boolean;
@Link relatedCellScrollDisMiss: boolean;
@Link draggingWeb: boolean;
@Link webScrollTop: boolean;
loadHtmlData() {
try {
// 点击按钮时,通过loadData,加载HTML格式的文本数据
this.controller.loadData(
\<html lang=\"en\">\ <head>\ <meta charset=\"UTF-8\">\ <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no\">\ <link rel="stylesheet" type="text/css" href="resource://rawfile/font.css">\ <link rel="stylesheet" type="text/css" href="resource://rawfile/newdetail.min.css">\ <script src="resource://rawfile/newdetail.min.js" type="text/javascript"></script>\ </head>\ <div class='app_new_detail fontml songtift modelbai hasimgs harmonyospage'>\ ${this.contentString} </div>\ </html>
,
“text/html”,
“UTF-8”,
" ",
" "
);
} catch (error) {
let e: business_error.BusinessError = error as business_error.BusinessError;
}
}
@Prop messageHandler?: messageHandler;
@Link webScrollBottom: boolean;
//记录上次网页的偏移量
private lastOffset: number = 0;
private screenHeight = px2vp(display.getDefaultDisplaySync()
.height) - TPUtil.getSafeAreaTopHeight() - TPUtil.getSafeAreaBottomHeight() - 44;
aboutToAppear(): void {
web_webview.WebviewController.setWebDebuggingAccess(true)
}
aboutToDisappear(): void {
}
controller: web_webview.WebviewController = new web_webview.WebviewController();
/**
*/
build() {
ListItem() {
Stack() {
// 组件创建时,加载www.example.com
Web({ src: ‘’, controller: this.controller })
.height(TPCommonConstants.FULL_LENGTH)
.width(TPCommonConstants.FULL_LENGTH)
.javaScriptProxy({
object: this.messageHandler,
name: “messageHandler”,
methodList: [“returnHeight”, “media”],
controller: this.controller
})
.onPageEnd(e => {
this.messageHandler!.bindController(this.controller)
this.controller.runJavaScript(‘webOnload(``)’)
})
.onProgressChange(e => {
})
.onConsole(e => {
return true;
})
.onControllerAttached(() => {
this.loadHtmlData();
})
.onConsole((e) => {
return true;
})
.overScrollMode(OverScrollMode.NEVER)
.onTouch((event: TouchEvent) => {
this.draggingWeb = true;
event.stopPropagation()
})
.layoutWeight(1)
Button('网页刷新').onClick((event: ClickEvent) => {
this.loadHtmlData()
}).width(100)
.height(100)
}.width(TPCommonConstants.FULL_LENGTH)
.height(this.webHeight > this.screenHeight ? this.screenHeight : this.webHeight)
}.id("webview")
}
onPageShow(): void {
// setTimeout(() => {
// this.loadHtmlData();
// }, 0)
}
}
但是当网页渲染完成之后,我们调用js方法获取网页高度,h5给我们返回的高度
总是第一次错误,第二次才返回正确的,后来发现
我们初始化webview的时候,默认高度不能是0,要给一个默认高度,
这样的话才能正确的获取到网页内容高度