Read the original article:How to get the width of a web component
Context
Partners want to obtain the width of the front-end web page loaded by the Web component, and also need a method to obtain the width of the Web component. However, the official API only provides the getPageHeight() method to obtain the page height of the current web page, and does not provide an API to obtain the page width.
Description
To get the width of a web component, you can use componentUtils.getRectangleById to get the width of the component in the obtained component information. For reference: Get component information Currently, there is no API for getting the width of a web page. You can only use the front-end method to get it, and then pass it to the application side through jsBridge. For reference: The application side calls the front-end page function
Solution
To get the width of a Web component, you need to first identify the Web component with an id, then get the component information through componentUtils.getRectangleById, and then call size.width under the component information object to get the width. Because it needs to be aligned with the width obtained from the front-end web page, you need to use px2vp to convert pixels (px) to visual pixels (vp). There are many ways to write js on the front end to get the width of the front-end web page, such as:
<script>
function getWidth(){
return window.innerWidth;
}
getWidth();
</script>
After obtaining the width on the front end, you can call runJavaScript on the application side to obtain the js execution result.
For a complete example, please refer to the following demo:
import { webview } from '@kit.ArkWeb';
import { componentUtils } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct WebComponent {
controller: webview.WebviewController = new webview.WebviewController();
@State webResult: string = '';
build() {
Column() {
// Get component width
Button('Get Component Width')
.onClick(() => {
// Get the component info object, then access size.width from the object
try {
let obj: componentUtils.ComponentInfo = componentUtils.getRectangleById('1');
console.log('width is:', px2vp(obj.size.width));
} catch (error) {
// TODO: Implement error handling.
}
})
.margin({ top: 20, left: 10 })
.fontSize(10)
Web({ src: 'www.baidu.com', controller: this.controller })
.onControllerAttached(() => {
// Set custom user agent string
this.controller.setCustomUserAgent(
'Mozilla/5.0 (Linux; Android 9; VRD-AL10; HMSCore 6.3.0.331) AppleWebKit/537.36 ' +
'(KHTML, like Gecko) Chrome/99.0.4844.88 HuaweiBrowser/12.0.4.1 Mobile Safari/537.36'
);
})
.id('1')
.onPageEnd(e => {
// Execute JS in the web page to get its width
this.controller.runJavaScript(
'function getWidth(){\n' +
' return window.innerWidth;\n' +
'}\n' +
'getWidth();',
// Get the JS execution result in the callback
(error, result) => {
if (error) {
console.error(`run JavaScript error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
return;
}
if (result) {
this.webResult = result;
console.info(`The width return value is: ${result}`);
}
});
})
.domStorageAccess(true)
.javaScriptAccess(true)
.fileAccess(true)
.mixedMode(MixedMode.All)
.width(200)
}
}
}
Common FAQ
Q: Why is the screen width obtained through the getWindowProperties system method inconsistent with the width obtained through window.innerWidth method in the H5 loaded by Web?
A: The width obtained through the getWindowProperties system method is the current window size, i.e., the screen resolution width, with units in px. The width obtained through the window.innerWidth method is the layout viewport height. If width=device-width is added to the viewport’s content in H5, it means the current H5 has adapted to the current device size, and the obtained width is the Web component’s width, with units in vp. If not added, browsers on devices will set their default viewport to 980px or 1024px (or other values, decided by the device itself), with units in px.
If you want to get the screen width in H5, you can use window.screen.width, with units in vp. Using vp2px and px2vp methods, px and vp can be converted to each other.
Constraints and Limitations
- This example supports API Version 19 Release and above.
- This example supports HarmonyOS 5.1. 1 Release SDK and above.
- This example requires DevEco Studio 5.1.1 Release or above for compilation and running.
Key Takeaways
- Use getRectangleById with component id to get Web component’s width in px
- Convert px to vp using px2vp for consistent units with front-end
- Use front-end JavaScript (e.g., document.documentElement.scrollWidth) to get web page width
- Pass front-end width to application using runJavaScript method
- Understand difference between screen width, window width, and viewport width in web context
Reference Link
- Getting Component Information
- Calling Front-end Page Functions from Application Side
- getWindowProperties API
- vp2px and px2vp Methods

Top comments (0)