@ionic-native/in-app-browser
This project is developed based on @ionic-native/in-app-browser@5.36.0.
Introduction
A plugin for loading web pages inside applications. It provides a full-featured browser view and supports custom toolbars, navigation controls, and more. It is compatible with Android, iOS, and OpenHarmony platforms, providing unified browser management capabilities for cross-platform app development. This document mainly describes usage on the OpenHarmony system.
In mobile app development, an in-app browser is an important part of improving user experience. The @ionic-native/in-app-browser plugin wraps native platform APIs and provides unified cross-platform interfaces, allowing developers to implement in-app browser display, hiding, and customization without deep native development.
Supported Platforms
- OpenHarmony: 5.0+
Installation
You can quickly install the plugin through command-line installation or manual integration. Installation from the npm repository is supported.
Command-line Installation (Recommended)
Install hionic CLI:
npm install -g hionic
Choose one of the following two methods only.
npm installation:
# Install plugin
npm install @ionic-native/in-app-browser
# Sync plugin
hionic sync
hionic CLI installation:
hionic plugin add @ionic-native/in-app-browser
Manual Integration
1. Add Plugin Configuration
According to the config-json item in plugin.xml, locate the config.xml file in the entry module and add configuration according to the param tag:
<feature name="InAppBrowser">
<param name="harmony-package" value="InAppBrowser" />
<param name="onload" value="true" />
</feature>
2. Update CMake Configuration
According to the CMakeLists item in plugin.xml, locate module cordova. The path is the CMakeLists.txt file specified by target. Add add_library:
add_library(cordova SHARED
// ...
inappbrowser/InAppBrowser.cpp
// ...
)
3. Copy Source Files
According to the source-file item in plugin.xml, copy source code from the src path to the directory specified by target-dir in the cordova module:
Copy InAppBrowser.h and InAppBrowser.cpp from src/main/cpp/inappbrowser in the source code to src/main/cpp/inappbrowser in the cordova module.
Copy BrowserAction.ets from src/main/ets/components/inappbrowserAction in the source code to src/main/ets/components/inappbrowserAction in the cordova module.
4. Add ArkTS Configuration
In the build-profile.json5 file of the cordova module, add the ets file path copied in step 3 to the buildOption/arkOptions/runtimeOnly/sources configuration array:
"buildOption":{
"arkOptions": {
"runtimeOnly": {
"sources": [
// ...
"./src/main/ets/components/inappbrowserAction/BrowserAction.ets"
// ...
]
}
}
}
Uninstallation
# Uninstall via hionic CLI
hionic plugin remove @ionic-native/in-app-browser
Constraints and Limitations
Compatibility
Tested successfully on the following version:
- SDK: 5.0.5(17); IDE: DevEco Studio: 6.0.0; ROM: 5.1.0.150;
Permission Requirements
Not involved.
Usage Examples
Example 1: Open web page in-app
Implements displaying in-app browser and loading web page.
import { InAppBrowser } from "@ionic-native/in-app-browser";
// Call create method to create browser window
const browser = InAppBrowser.create("https://www.example.com",
'_blank',
'location=yes,hidden=no,closebuttoncolor=#ff0000,fullscreen=yes');
// Add beforeload listener
browser.addEventListener("beforeload", function(url){
console.log("beforeload function:"+url);
});
// Add loadstart listener
browser.addEventListener("loadstart", function(){
console.log("loadstart function");
});
// Add loadstop listener
browser.addEventListener("loadstop", function(){
// Execute js and return arrayBuffer data
browser.executeScript({code:"function test(){console.log('execute function');
let buffer = new ArrayBuffer(1);
let view = new Uint8Array(buffer);
view[0] = 255; return buffer;} test();"},function(message){
// Return value of js execution supports string/number/bool/array/arrayBuffer
function stringToUint8Array(str){
var arr = [];
for (var i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
}
var tmpUint8Array = new Uint8Array(arr);
return tmpUint8Array
}
var temp = stringToUint8Array(atob(message));
console.log("execute callback:" + temp[0]);
});
// Execute js and call postMessage to notify main browser
browser.executeScript({ code: "
var message = 'this is the message';
var messageObj = {my_message: message};
var stringifiedMessageObj = JSON.stringify(messageObj);
cordova_iab.postMessage(stringifiedMessageObj);"
});
// Load rawfile/www/js/test.js, www.example.com: default rawfile domain
browser.executeScript({ file: "https://www.example.com/www/js/test.js" }, function(){
browser.executeScript({ code:"test();" });
console.log("execute callback:");
});
// Load online js, cross-origin loading supported
browser.executeScript({ file: "https://www.*****.com/js/test.js" });
// Load rawfile/www/js/test.css, www.example.com: default rawfile domain
browser.insertCSS({ file: "https://www.example.com/css/test.css" });
// Load online css
browser.insertCSS({ file: "https://www.****.com/css/test.css" }, function(){
console.log("css execute callback");
});
// Insert css code, no callback
browser.insertCSS({ code: "body{font-size:200px;}" });
// Insert css code, with callback
browser.insertCSS({ code: "body{font-size:200px;}" }, function(){
console.log("css execute callback");
});
console.log("loadstop function");
});
// Add message listener
browser.addEventListener("message", function(message){
console.log("message function:"+message);
});
// Add exit listener
browser.addEventListener("exit", function(){
console.log("exit function");
});
// Add download listener
browser.addEventListener("download", function(paras){
// App can set saved filename based on download url
console.log("download:"+JSON.stringify(paras));
function downloadInAppBrowser(uri, fileName) {
function onErrorReadFile(error) {
}
function successFun(fileEntry) {
}
function failFun(error) {
console.log("An error has occurred: Code = " + error.code);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
}
function progressFun(progressEvent) {
var progress = progressEvent.loaded / progressEvent.total * 100;
console.log("download:"+progress);
}
window.resolveLocalFileSystemURL(cordova.file.externalDataDirectory,
function(dirEntry) {
var targetPath = dirEntry.toURL() + fileName;
var fileTransfer = new FileTransfer();
fileTransfer.onprogress = progressFun;
fileTransfer.download(
uri,
targetPath,
successFun,
failFun,
false,
{}
);
});
}
downloadInAppBrowser(paras.url, "test.app");
});
// Add customscheme listener
browser.addEventListener("customscheme", function(para){
console.log("customscheme function:"+JSON.stringify(para));
});
// Show browser
browser.show();
// Hide browser
browser.hide();
// Close browser
browser.close();
Usage Guide
The plugin exposes all functional APIs under the global object InAppBrowser. Before use, ensure the device-ready event (deviceready) has been triggered.
1. Create browser window
Open a browser window inside the app.
Method signature
const inAppBrowserRef = InAppBrowser.create(url, target, options)
Parameter description
| Parameter | Type | Description |
|---|---|---|
url |
string |
URL to load |
target |
string |
Open mode: _blank (new page), _system (system browser), _self (in-app) |
options |
string |
Browser configuration options |
2. Show browser window
Show hidden browser window (must first be hidden via hidden=yes).
Method signature
inAppBrowserRef.show()
3. Hide browser window
Hide browser window (not closed, can be shown again via show()).
Method signature
inAppBrowserRef.hide()
4. Close browser window
Close browser window and release resources.
Method signature
inAppBrowserRef.close()
5. Execute JavaScript code
Execute JavaScript code in browser page, supports injecting script files or inline code.
Method signature
inAppBrowserRef.executeScript(options, callback)
Parameter description
| Parameter | Type | Description |
|---|---|---|
options.code |
string |
Inline JavaScript code to execute |
options.file |
string |
External script file URL to inject |
callback |
function |
Callback after execution |
6. Insert CSS styles
Insert CSS styles into browser page, supports injecting style files or inline styles.
Method signature
inAppBrowserRef.insertCSS(options, callback)
Parameter description
| Parameter | Type | Description |
|---|---|---|
options.code |
string |
Inline CSS code to insert |
options.file |
string |
External CSS file URL to inject |
callback |
function |
Callback after insertion |
7. Add event listeners
Listen to plugin events.
Method signature
inAppBrowserRef.addEventListener(eventName, callback)
Supported event types
| Event name | Trigger timing | Event parameters |
|---|---|---|
loadstart |
When page starts loading | url: currently loading URL |
loadstop |
When page load is complete | url: currently loaded URL |
loaderror |
When page load fails | url: failed URL, code: error code, message: error message |
exit |
When browser window is closed | None |
beforeload |
Before page loads a new URL | url: URL about to load |
message |
When browser page sends message to app | data: message content |
Configuration
The following configuration values are available:
| Data | Type | Description |
|---|---|---|
location |
string |
Whether to show address bar, yes to show, no to hide |
hidden |
string |
Whether to hide browser, yes to hide, no to show |
fullscreen |
string |
Whether to show full screen, yes full screen, no not full screen |
closebuttoncolor |
string |
Close button color |
toolbar |
string |
Whether to show toolbar, yes to show, no to hide |
toolbarposition |
string |
Toolbar position, top top, bottom bottom |
hidenavigationbuttons |
string |
Whether to hide navigation buttons, yes hide, no show |
clearcache |
string |
Whether to clear cache before opening, yes clear, no do not clear |
clearsessioncache |
string |
Whether to clear session cache, yes clear, no do not clear |
Example
Core Configuration (config.xml)
All browser-related configurations must be declared in config.xml under the project's rawfile directory. Complete example:
Located in: config.xml
<!-- Show address bar -->
<preference name="InAppBrowserLocation" value="yes" />
<!-- Show browser by default -->
<preference name="InAppBrowserHidden" value="no" />
<!-- Fullscreen display -->
<preference name="InAppBrowserFullscreen" value="yes" />
<!-- Close button color -->
<preference name="InAppBrowserCloseButtonColor" value="#ff0000" />
<!-- Show toolbar -->
<preference name="InAppBrowserToolbar" value="yes" />
<!-- Toolbar at top -->
<preference name="InAppBrowserToolbarPosition" value="top" />
<!-- Show navigation buttons -->
<preference name="InAppBrowserHideNavigationButtons" value="no" />
<!-- Do not clear cache before open -->
<preference name="InAppBrowserClearCache" value="no" />
<!-- Do not clear session cache -->
<preference name="InAppBrowserClearSessionCache" value="no" />
Directory Structure
|---- Directory
| |---- src/main # Plugin implementation code
| |---- cpp # C++ code
| |---- ets # ArkTS code
| |---- www # Web-side code
| |---- README.md # Documentation
| |---- package.json # Configuration file
| |---- plugin.xml # Plugin configuration file
Contributing
If you find any issues during usage, you can submit an Issue. You are also very welcome to submit a PR for co-development.
License
This plugin is open-sourced under the Apache License 2.0. See the LICENSE file for details.