### InAppBrowser Event Listeners Example
Source: https://github.com/apache/cordova-plugin-inappbrowser/blob/master/README.md
This example demonstrates how to use InAppBrowser event listeners for loadstart, loadstop, loaderror, beforeload, and message events. It also shows how to execute scripts and insert CSS into the InAppBrowser window.
```javascript
function showHelp(url) {
let inAppBrowserRef = cordova.InAppBrowser.open(url, "_blank", "location=yes,hidden=yes,beforeload=yes");
inAppBrowserRef.addEventListener('loadstart', (inAppBrowserEvent) => {
document.getElementById("status-message").textContent = "loading please wait ...";
});
inAppBrowserRef.addEventListener('loadstop', (inAppBrowserEvent) => {
if (inAppBrowserRef == undefined) return;
inAppBrowserRef.insertCSS({ code: "body{font-size: 25px;}" });
inAppBrowserRef.executeScript({
code:
"
const message = 'this is the message';
const messageObj = {my_message: message};
const stringifiedMessageObj = JSON.stringify(messageObj);
webkit.messageHandlers.cordova_iab.postMessage(stringifiedMessageObj);
"
});
document.getElementById("status-message").textContent = "";
inAppBrowserRef.show();
});
inAppBrowserRef.addEventListener('loaderror', (inAppBrowserEvent) => {
document.getElementById("status-message").textContent = "";
const scriptErrorMesssage = alert(
`Sorry we cannot open that page. Message from the server is : ${inAppBrowserEvent.message}`
);
inAppBrowserRef.executeScript(
{ code: scriptErrorMesssage },
// callback
(params) => {
if (params[0] == null) {
document.getElementById("status-message").textContent =
`Sorry we couldn't open that page. Message from the server is : '${params.message}'`;
}
}
);
inAppBrowserRef.close();
inAppBrowserRef = undefined;
});
inAppBrowserRef.addEventListener('beforeload', (inAppBrowserEvent, callback) => {
if (inAppBrowserEvent.url.startsWith("http://www.example.com/")) {
// Load this URL in the inAppBrowser.
callback(inAppBrowserEvent.url);
} else {
// The callback is not invoked, so the page will not be loaded.
document.getElementById("status-message").textContent = "This browser only opens pages on http://www.example.com/";
}
});
inAppBrowserRef.addEventListener('message', (inAppBrowserEvent) => {
document.getElementById("status-message").textContent = `message received: ${inAppBrowserEvent.data.my_message}`;
});
}
```
--------------------------------
### Basic InAppBrowser Open and Loadstart Event
Source: https://github.com/apache/cordova-plugin-inappbrowser/blob/master/README.md
Open the InAppBrowser and attach a listener to the 'loadstart' event to capture the URL when a page begins loading. This is a fundamental example for interacting with the InAppBrowser.
```javascript
var ref = cordova.InAppBrowser.open('https://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstart', function(event) { alert(event.url); });
```
--------------------------------
### Open InAppBrowser and Inject CSS on Load Stop
Source: https://github.com/apache/cordova-plugin-inappbrowser/blob/master/README.md
Opens a URL in a new InAppBrowser window and injects a CSS file once the page has finished loading. This example demonstrates event handling and CSS injection.
```javascript
var ref = cordova.InAppBrowser.open('https://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstop', function() {
ref.insertCSS({file: "mystyles.css"});
});
```
--------------------------------
### Install Cordova InAppBrowser Plugin
Source: https://github.com/apache/cordova-plugin-inappbrowser/blob/master/README.md
Use this command to add the InAppBrowser plugin to your Cordova project.
```bash
cordova plugin add cordova-plugin-inappbrowser
```
--------------------------------
### InAppBrowser Test Page Setup
Source: https://github.com/apache/cordova-plugin-inappbrowser/blob/master/tests/resources/local.html
This JavaScript code sets up an event listener for the 'deviceready' event to configure the InAppBrowser test page. It updates the hint text based on whether the device is running Cordova WebView.
```javascript
function onDeviceReady() { document.getElementById("hint").textContent = "Running CordovaWebView, deviceVersion=" + device.version + ", no toolbar should be present, Back link should work, logcat should NOT have failed 'gap:' calls."; } document.addEventListener("deviceready", onDeviceReady, false);
```
--------------------------------
### Handle Help Topic Selection
Source: https://github.com/apache/cordova-plugin-inappbrowser/blob/master/README.md
JavaScript code to handle user selection from the help topic dropdown. It determines the appropriate URL based on the user's choice and calls a function to display it.
```javascript
$('#help-select').on('change', function (e) {
var url;
switch (this.value) {
case "article":
url = "https://cordova.apache.org/docs/en/latest/"
+ "reference/cordova-plugin-inappbrowser/index.html";
break;
case "video":
url = "https://youtu.be/F-GlVrTaeH0";
break;
case "search":
url = "https://www.google.com/#q=inAppBrowser+plugin";
break;
}
showHelp(url);
});
```
--------------------------------
### HTML for Help Page Selection
Source: https://github.com/apache/cordova-plugin-inappbrowser/blob/master/README.md
Provides an HTML select element for users to choose a help topic. This is the user interface for initiating help requests.
```html
```
--------------------------------
### Override window.open with InAppBrowser
Source: https://github.com/apache/cordova-plugin-inappbrowser/blob/master/README.md
Hook window.open during initialization to route all page loads through the InAppBrowser.
```javascript
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
window.open = cordova.InAppBrowser.open;
}
```
--------------------------------
### Display Loading Status Message
Source: https://github.com/apache/cordova-plugin-inappbrowser/blob/master/README.md
Callback function for the 'loadstart' event. It updates a status message to inform the user that the page is loading.
```javascript
function loadStartCallBack() {
$('#status-message').text("loading please wait ...");
}
```
--------------------------------
### Open Local URLs with InAppBrowser
Source: https://github.com/apache/cordova-plugin-inappbrowser/blob/master/README.md
Demonstrates opening local HTML files using the InAppBrowser plugin. It shows how to load content within the Cordova WebView, the system browser, or the InAppBrowser itself, with options to control the location bar.
```javascript
var iab = cordova.InAppBrowser;
iab.open('local-url.html'); // loads in the Cordova WebView
iab.open('local-url.html', '_self'); // loads in the Cordova WebView
iab.open('local-url.html', '_system'); // Security error: system browser, but url will not load (iOS)
iab.open('local-url.html', '_blank'); // loads in the InAppBrowser
iab.open('local-url.html', 'random_string'); // loads in the InAppBrowser
iab.open('local-url.html', 'random_string', 'location=no'); // loads in the InAppBrowser, no location bar
```
--------------------------------
### Open In-App Browser
Source: https://github.com/apache/cordova-plugin-inappbrowser/blob/master/README.md
Opens a URL in a new in-app browser window. This function is a drop-in replacement for the standard `window.open()`.
```javascript
var ref = cordova.InAppBrowser.open('https://apache.org', '_blank', 'location=yes');
```
--------------------------------
### cordova.InAppBrowser.open
Source: https://github.com/apache/cordova-plugin-inappbrowser/blob/master/README.md
Opens a URL in a new InAppBrowser instance, the current browser instance, or the system browser. It returns a reference to the InAppBrowser window for '_blank' targets.
```APIDOC
## cordova.InAppBrowser.open
### Description
Opens a URL in a new `InAppBrowser` instance, the current browser instance, or the system browser.
### Method
`cordova.InAppBrowser.open(url, target, options)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters
- __ref__: Reference to the `InAppBrowser` window when the target is set to `'_blank'`. _(InAppBrowser)_ On Android, non-whitelisted URLs also fall back to the `InAppBrowser` when the target is set to `'_self'`.
- __url__: The URL to load _(String)_. Call `encodeURI()` on this if the URL contains Unicode characters.
- __target__: The target in which to load the URL, an optional parameter that defaults to `_self`. _(String)_
- `_self`: Opens in the Cordova WebView. On Android, non-whitelisted URLs fall back to the `InAppBrowser`. On iOS, the current implementation does not perform this fallback and navigation remains in the Cordova WebView (subject to ``).
- `_blank`: Opens in the `InAppBrowser`.
- `_system`: Opens in the system's web browser.
- __options__: Options for the `InAppBrowser`. Optional, defaulting to: `location=yes`. _(String)_ The `options` string must not contain any blank space, and each feature's name/value pairs must be separated by a comma. Feature names are case insensitive.
All platforms support:
- __location__: Set to `yes` or `no` to turn the `InAppBrowser`'s location bar on or off.
Android supports these additional options:
### Request Example
```javascript
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
```
### Response
#### Success Response (200)
- __ref__: Reference to the `InAppBrowser` window (for `_blank` target).
```
--------------------------------
### Handle Download Event
Source: https://github.com/apache/cordova-plugin-inappbrowser/blob/master/README.md
Implement a listener for the 'download' event to intercept file downloads initiated within the InAppBrowser. This allows you to access download details like URL and MIME type.
```javascript
function downloadListener(params){
var url = params.url;
var mimetype = params.mimetype;
var xhr = new XMLHttpRequest();
xhr.open("GET", params.url);
xhr.onload = function() {
var content = xhr.responseText;
};
xhr.send();
}
```
--------------------------------
### Open URL in InAppBrowser
Source: https://github.com/apache/cordova-plugin-inappbrowser/blob/master/README.md
Opens a URL in a new InAppBrowser instance, the current browser instance, or the system browser. The 'ref' variable provides a reference to the InAppBrowser window when target is '_blank'.
```javascript
var ref = cordova.InAppBrowser.open(url, target, options);
```
--------------------------------
### cordova.InAppBrowser.open
Source: https://github.com/apache/cordova-plugin-inappbrowser/blob/master/README.md
Opens a new InAppBrowser window to display the specified URL. Various options can be passed to customize the browser's appearance and functionality.
```APIDOC
## cordova.InAppBrowser.open
### Description
Opens a new InAppBrowser window to display the specified URL. Various options can be passed to customize the browser's appearance and functionality.
### Parameters
#### Options
- **__hidden__** (string) - Optional - Set to `yes` to create the browser and load the page, but not show it. Defaults to `no`.
- **__beforeload__** (string) - Optional - Set to enable the `beforeload` event to modify which pages are actually loaded in the browser. Accepted values are `get`, `post`, or `yes`. Note that POST requests are not currently supported.
- **__clearcache__** (string) - Optional - Set to `yes` to clear the shared browser's cookie cache before the in-app browser is opened.
- **__clearsessioncache__** (string) - Optional - Set to `yes` to clear the shared session cookies from the browser's cache before the in-app browser is opened.
- **__closebuttoncaption__** (string) - Optional - Set to a string to use as the close button's caption instead of a X. Requires localization.
- **__closebuttoncolor__** (string) - Optional - Set to a valid hex color string (e.g., `#00ff00`) to change the close button color. Only effective if user has location set to `yes`.
- **__footer__** (string) - Optional - Set to `yes` to show a close button in the footer. Use `__closebuttoncaption__` and `__closebuttoncolor__` to set its properties.
- **__footercolor__** (string) - Optional - Set to a valid hex color string (e.g., `#00ff00` or `#CC00ff00`) to change the footer color. Only effective if `__footer__` is set to `yes`.
- **__hardwareback__** (string) - Optional - Set to `yes` to use the hardware back button for navigation within the `InAppBrowser`'s history. Defaults to `yes`.
- **__hidenavigationbuttons__** (string) - Optional - Set to `yes` to hide the navigation buttons on the location toolbar. Only effective if location is set to `yes`. Defaults to `no`.
- **__hideurlbar__** (string) - Optional - Set to `yes` to hide the url bar on the location toolbar. Only effective if location is set to `yes`. Defaults to `no`.
- **__navigationbuttoncolor__** (string) - Optional - Set to a valid hex color string (e.g., `#00ff00`) to change the color of navigation buttons. Only effective if location is set to `yes` and `__hidenavigationbuttons__` is not set to `yes`.
- **__toolbarcolor__** (string) - Optional - Set to a valid hex color string (e.g., `#00ff00`) to change the color of the toolbar. Only effective if location is set to `yes`.
- **__lefttoright__** (string) - Optional - Set to `yes` to swap positions of the navigation buttons and the close button. Defaults to `no`.
- **__zoom__** (string) - Optional - Enables pinch-to-zoom gesture. Set to `no` to disable it. Defaults to `yes`.
- **__zoomcontrols__** (string) - Optional - Set to `yes` to show Android browser's zoom controls, set to `no` to hide them. Defaults to `yes`. Deprecated since Android API Level 26.
- **__mediaPlaybackRequiresUserAction__** (string) - Optional - Set to `yes` to prevent HTML5 audio or video from autoplaying. Defaults to `no`.
- **__shouldPauseOnSuspend__** (string) - Optional - Set to `yes` to make InAppBrowser WebView pause/resume with the app to stop background audio.
- **__useWideViewPort__** (string) - Optional - Sets whether the WebView should enable support for the "viewport" HTML meta tag. Defaults to `yes`.
- **__fullscreen__** (string) - Optional - Sets whether the InappBrowser WebView is displayed fullscreen or not. In fullscreen mode, the status bar is hidden. Default value is `yes`.
### iOS Specific Options
(Additional options specific to iOS are mentioned but not detailed in the source text.)
```
--------------------------------
### InAppBrowser.show
Source: https://github.com/apache/cordova-plugin-inappbrowser/blob/master/README.md
Makes the InAppBrowser window visible. This is typically used after the browser has been opened in a hidden state (e.g., using the `hidden=yes` option).
```APIDOC
## InAppBrowser.show
### Description
Shows the `InAppBrowser` window. This is useful if the browser was initially opened with the `hidden` option set to `yes`.
### Method Signature
`ref.show();`
### Parameters
- __ref__: (InAppBrowser) - A reference to the `InAppBrowser` window.
### Example
```javascript
// Assuming 'browserRef' is a valid InAppBrowser reference opened with hidden=yes
// browserRef.show();
```
```
--------------------------------
### Replace window.open with InAppBrowser
Source: https://github.com/apache/cordova-plugin-inappbrowser/blob/master/README.md
Replaces the global `window.open` function with `cordova.InAppBrowser.open`. Be aware of potential unintended side effects if this plugin is only a dependency.
```javascript
window.open = cordova.InAppBrowser.open;
```
--------------------------------
### InAppBrowser.show
Source: https://github.com/apache/cordova-plugin-inappbrowser/blob/master/README.md
Displays an InAppBrowser window that was opened hidden. Calling this has no effect if the InAppBrowser was already visible.
```APIDOC
## InAppBrowser.show
### Description
Displays an InAppBrowser window that was opened hidden. Calling this has no effect if the InAppBrowser was already visible.
### Method
JavaScript Method
### Parameters
#### Path Parameters
- __ref__ (InAppBrowser) - Required - Reference to the InAppBrowser window.
### Supported Platforms
- Android
- Browser
- iOS
### Quick Example
var ref = cordova.InAppBrowser.open('https://apache.org', '_blank', 'hidden=yes');
// some time later...
ref.show();
```
--------------------------------
### Show InAppBrowser After Content Loads
Source: https://github.com/apache/cordova-plugin-inappbrowser/blob/master/README.md
Callback function for the 'loadstop' event. It injects CSS, clears the status message, and makes the InAppBrowser visible after the page content has fully loaded.
```javascript
function loadStopCallBack() {
if (inAppBrowserRef != undefined) {
inAppBrowserRef.insertCSS({ code: "body{font-size: 25px;}" });
$('#status-message').text("");
inAppBrowserRef.show();
}
}
```
--------------------------------
### Open URL in InAppBrowser
Source: https://github.com/apache/cordova-plugin-inappbrowser/blob/master/README.md
Opens a specified URL in a new InAppBrowser window. The `location=yes` option enables the address bar.
```javascript
var ref = cordova.InAppBrowser.open('https://apache.org', '_blank', 'location=yes');
```
```javascript
var ref2 = cordova.InAppBrowser.open(encodeURI('http://ja.m.wikipedia.org/wiki/ハングル'), '_blank', 'location=yes');
```
--------------------------------
### InAppBrowser.executeScript
Source: https://github.com/apache/cordova-plugin-inappbrowser/blob/master/README.md
Injects JavaScript code into the InAppBrowser window. (Only available when the target is set to '_blank')
```APIDOC
## InAppBrowser.executeScript
### Description
Injects JavaScript code into the `InAppBrowser` window. (Only available when the target is set to `'_blank'`)
### Method
JavaScript Method
### Parameters
#### Path Parameters
- __ref__ (InAppBrowser) - Required - Reference to the `InAppBrowser` window.
- __injectDetails__ (Object) - Required - Details of the script to run, specifying either a `file` or `code` key.
- __file__ (string) - URL of the script to inject.
- __code__ (string) - Text of the script to inject.
- __callback__ (function) - The function that executes after the JavaScript code is injected.
- If the injected script is of type `code`, the callback executes
with a single parameter, which is the return value of the
script, wrapped in an `Array`. For multi-line scripts, this is
the return value of the last statement, or the last expression
evaluated.
### Supported Platforms
- Android
- Browser
- iOS
### Quick Example
var ref = cordova.InAppBrowser.open('https://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstop', function() {
ref.executeScript({file: "myscript.js"});
});
### Browser Quirks
- only __code__ key is supported.
```
--------------------------------
### Open Whitelisted URLs with InAppBrowser
Source: https://github.com/apache/cordova-plugin-inappbrowser/blob/master/README.md
Illustrates how to open whitelisted URLs using the InAppBrowser plugin. This includes loading content in the Cordova WebView, system browser, or InAppBrowser, with an option to hide the location bar.
```javascript
var iab = cordova.InAppBrowser;
iab.open('https://whitelisted-url.com'); // loads in the Cordova WebView
iab.open('https://whitelisted-url.com', '_self'); // loads in the Cordova WebView
iab.open('https://whitelisted-url.com', '_system'); // loads in the system browser
iab.open('https://whitelisted-url.com', '_blank'); // loads in the InAppBrowser
iab.open('https://whitelisted-url.com', 'random_string'); // loads in the InAppBrowser
iab.open('https://whitelisted-url.com', 'random_string', 'location=no'); // loads in the InAppBrowser, no location bar
```
--------------------------------
### Show InAppBrowser Window
Source: https://github.com/apache/cordova-plugin-inappbrowser/blob/master/README.md
Displays an InAppBrowser window that was previously hidden. This method is useful for bringing a hidden browser window back into view. It is supported on Android, Browser, and iOS.
```javascript
ref.show();
```
```javascript
var ref = cordova.InAppBrowser.open('https://apache.org', '_blank', 'hidden=yes');
// some time later...
ref.show();
```
--------------------------------
### Open Non-Whitelisted URLs with InAppBrowser
Source: https://github.com/apache/cordova-plugin-inappbrowser/blob/master/README.md
Shows how to open URLs that are not whitelisted. Behavior varies by platform: Android falls back to InAppBrowser, while iOS is controlled by Cordova WebView rules. Options include loading in the system browser or InAppBrowser, with or without a location bar.
```javascript
var iab = cordova.InAppBrowser;
iab.open('https://url-that-fails-whitelist.com'); // loads in the InAppBrowser
iab.open('https://url-that-fails-whitelist.com', '_self'); // Android: loads in the InAppBrowser, iOS: handled by Cordova WebView rules
iab.open('https://url-that-fails-whitelist.com', '_system'); // loads in the system browser
iab.open('https://url-that-fails-whitelist.com', '_blank'); // loads in the InAppBrowser
iab.open('https://url-that-fails-whitelist.com', 'random_string'); // loads in the InAppBrowser
iab.open('https://url-that-fails-whitelist.com', 'random_string', 'location=no'); // loads in the InAppBrowser, no location bar
```
--------------------------------
### Display Local URL
Source: https://github.com/apache/cordova-plugin-inappbrowser/blob/master/tests/resources/local.html
This JavaScript code snippet demonstrates how to display the current URL of the loaded page using `document.write(location.href)`. This is useful for verifying that a local URL has been successfully loaded.
```javascript
document.write(location.href)
```
--------------------------------
### InAppBrowser.addEventListener
Source: https://github.com/apache/cordova-plugin-inappbrowser/blob/master/README.md
Adds a listener for events originating from the InAppBrowser window. This is particularly useful when the browser is opened with the '_blank' target, allowing developers to react to various states like page loading, errors, or window closure.
```APIDOC
## InAppBrowser.addEventListener
### Description
Adds a listener for an event from the `InAppBrowser`. This method is only available when the `InAppBrowser` is opened with the target set to `'_blank'`.
### Method Signature
`ref.addEventListener(eventname, callback);`
### Parameters
- __ref__: (InAppBrowser) - A reference to the `InAppBrowser` window.
- __eventname__: (String) - The name of the event to listen for. Supported events include:
- `loadstart`: Fires when the `InAppBrowser` begins loading a URL.
- `loadstop`: Fires when the `InAppBrowser` completes loading a URL.
- `loaderror`: Fires when an error occurs during URL loading.
- `exit`: Fires when the `InAppBrowser` window is closed.
- `beforeload`: Fires before an URL is loaded, allowing for interception if the `beforeload` option is enabled.
- `message`: Fires when a message is received from the page loaded within the `InAppBrowser`.
- `customscheme`: Fires when a link matching `AllowedSchemes` is followed.
- `download`: (Android Only) Fires when the loaded URL results in a file download.
- __callback__: (Function) - The function to execute when the specified event fires. It receives an `InAppBrowserEvent` object as an argument.
### Example
```javascript
function setupInAppBrowserListeners(inAppBrowserRef) {
inAppBrowserRef.addEventListener('loadstart', (event) => {
console.log('Page loading started:', event.url);
});
inAppBrowserRef.addEventListener('loadstop', (event) => {
console.log('Page loading finished:', event.url);
// Example: Inject CSS after page loads
inAppBrowserRef.insertCSS({ code: "body { background-color: lightblue; }" });
});
inAppBrowserRef.addEventListener('loaderror', (event) => {
console.error('Page loading error:', event.message, 'URL:', event.url);
});
inAppBrowserRef.addEventListener('exit', (event) => {
console.log('InAppBrowser closed.');
});
inAppBrowserRef.addEventListener('beforeload', (event, callback) => {
console.log('Before load decision for URL:', event.url);
// Example: Only allow loading example.com
if (event.url.startsWith("http://www.example.com/")) {
callback(event.url);
} else {
console.log('Blocked navigation to:', event.url);
// Callback not invoked, page will not load
}
});
inAppBrowserRef.addEventListener('message', (event) => {
console.log('Message received from InAppBrowser:', event.data);
});
// Android only example
if (cordova.platformId === 'android') {
inAppBrowserRef.addEventListener('download', (event) => {
console.log('File download initiated:', event.url);
});
}
}
// Usage:
// let browserRef = cordova.InAppBrowser.open('https://example.com', '_blank', 'location=yes,hidden=yes,beforeload=yes');
// setupInAppBrowserListeners(browserRef);
```
```
--------------------------------
### InAppBrowser.executeScript
Source: https://github.com/apache/cordova-plugin-inappbrowser/blob/master/README.md
Executes a JavaScript string within the context of the InAppBrowser's current page. This allows for dynamic manipulation of the loaded content or interaction with the page's JavaScript environment.
```APIDOC
## InAppBrowser.executeScript
### Description
Executes a JavaScript script within the `InAppBrowser`'s web view.
### Method Signature
`ref.executeScript(details, [callback]);`
### Parameters
- __ref__: (InAppBrowser) - A reference to the `InAppBrowser` window.
- __details__: (Object) - An object containing the script to execute.
- __file__: (String) - URL of the JavaScript file to load.
- __code__: (String) - JavaScript code to execute.
- __allFrames__: (Boolean) - Whether to inject script into all frames (default is `false`).
- __callback__: (Function, optional) - A callback function that is invoked with an array of results from the script execution. If the script returns a value, it will be in the array. If an error occurs, the callback will receive an error object.
### Example
```javascript
// Execute a simple JavaScript code snippet
ref.executeScript({ code: "document.body.style.backgroundColor = 'red';" }, (results) => {
console.log('Script executed successfully:', results);
});
// Execute a JavaScript file
// ref.executeScript({ file: "path/to/your/script.js" });
```
```
--------------------------------
### Handle Custom Scheme Event
Source: https://github.com/apache/cordova-plugin-inappbrowser/blob/master/README.md
Listen for custom scheme events to trigger actions within your application when a specific URL is navigated to in the InAppBrowser. Ensure the custom scheme is added to the AllowedSchemes preference in config.xml.
```xml
```
```javascript
function onCustomScheme(e) {
if (e.url === 'app://hide') {
inAppBrowserRef.hide();
}
}
inAppBrowserRef = cordova.InAppBrowser.open('https://example.com', '_blank');
inAppBrowserRef.addEventListener('customscheme', onCustomScheme);
```
--------------------------------
### Execute JavaScript in InAppBrowser
Source: https://github.com/apache/cordova-plugin-inappbrowser/blob/master/README.md
Injects JavaScript code into the InAppBrowser window. This is only available when the target is set to '_blank'. For browser environments, only the 'code' key is supported in the details object.
```javascript
ref.executeScript(details, callback);
```
```javascript
var ref = cordova.InAppBrowser.open('https://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstop', function() {
ref.executeScript({file: "myscript.js"});
});
```
--------------------------------
### InAppBrowser.hide
Source: https://github.com/apache/cordova-plugin-inappbrowser/blob/master/README.md
Hides the InAppBrowser window. Calling this has no effect if the InAppBrowser was already hidden.
```APIDOC
## InAppBrowser.hide
### Description
Hides the InAppBrowser window. Calling this has no effect if the InAppBrowser was already hidden.
### Method
JavaScript Method
### Parameters
#### Path Parameters
- __ref__ (InAppBrowser) - Required - Reference to the InAppBrowser window.
### Supported Platforms
- Android
- iOS
### Quick Example
var ref = cordova.InAppBrowser.open('https://apache.org', '_blank');
// some time later...
ref.hide();
```
--------------------------------
### Configure Preferred Content Mode for iOS
Source: https://github.com/apache/cordova-plugin-inappbrowser/blob/master/README.md
Sets the preferred content mode for WKWebView on iOS to 'mobile', which forces the user agent to contain 'iPad'. This is useful for detecting iPads as mobile devices.
```xml
```
--------------------------------
### InAppBrowser.insertCSS
Source: https://github.com/apache/cordova-plugin-inappbrowser/blob/master/README.md
Injects CSS styles into the InAppBrowser's current page. This enables runtime modification of the page's appearance, such as changing fonts, colors, or layout.
```APIDOC
## InAppBrowser.insertCSS
### Description
Injects CSS styles into the `InAppBrowser`'s web view.
### Method Signature
`ref.insertCSS(details, [callback]);`
### Parameters
- __ref__: (InAppBrowser) - A reference to the `InAppBrowser` window.
- __details__: (Object) - An object containing the CSS to inject.
- __file__: (String) - URL of the CSS file to load.
- __code__: (String) - CSS code to inject.
- __allFrames__: (Boolean) - Whether to inject CSS into all frames (default is `false`).
- __callback__: (Function, optional) - A callback function that is invoked once the CSS has been injected.
### Example
```javascript
// Inject CSS code
ref.insertCSS({ code: "body { font-size: 16px; color: blue; }" }, () => {
console.log('CSS injected successfully.');
});
// Inject CSS from a file
// ref.insertCSS({ file: "path/to/your/styles.css" });
```
```
--------------------------------
### Handle Page Load Errors with InAppBrowser
Source: https://github.com/apache/cordova-plugin-inappbrowser/blob/master/README.md
This snippet shows how to handle page load errors by attempting to execute a script to display an alert. If script execution fails, it falls back to displaying the error message in a div. The InAppBrowser is closed after the attempt.
```javascript
function loadErrorCallBack(params) {
$('#status-message').text("");
var scriptErrorMesssage =
"alert('Sorry we cannot open that page. Message from the server is : "
+ params.message + "');"
inAppBrowserRef.executeScript({ code: scriptErrorMesssage }, executeScriptCallBack);
inAppBrowserRef.close();
inAppBrowserRef = undefined;
}
function executeScriptCallBack(params) {
if (params[0] == null) {
$('#status-message').text(
"Sorry we couldn't open that page. Message from the server is : '"
+ params.message + "'"
);
}
}
```
--------------------------------
### InAppBrowser.close
Source: https://github.com/apache/cordova-plugin-inappbrowser/blob/master/README.md
Closes the InAppBrowser window.
```APIDOC
## InAppBrowser.close
### Description
Closes the `InAppBrowser` window that was previously opened.
### Method Signature
```javascript
ref.close();
```
### Parameters
- __ref__ (InAppBrowser) - Required - A reference to the `InAppBrowser` window to be closed.
### Supported Platforms
- Android
- Browser
- iOS
### Example
```javascript
var ref = cordova.InAppBrowser.open('https://apache.org', '_blank', 'location=yes');
// To close the InAppBrowser window:
ref.close();
```
```
--------------------------------
### Open InAppBrowser with Hidden Option
Source: https://github.com/apache/cordova-plugin-inappbrowser/blob/master/README.md
Opens the InAppBrowser to a specified URL with options to hide the browser initially and show the location bar. The browser is hidden to allow content to load before user interaction.
```javascript
function showHelp(url) {
var target = "_blank";
var options = "location=yes,hidden=yes";
inAppBrowserRef = cordova.InAppBrowser.open(url, target, options);
inAppBrowserRef.addEventListener('loadstart', loadStartCallBack);
inAppBrowserRef.addEventListener('loadstop', loadStopCallBack);
inAppBrowserRef.addEventListener('loaderror', loadErrorCallBack);
}
```
--------------------------------
### Update User-Agent Display
Source: https://github.com/apache/cordova-plugin-inappbrowser/blob/master/tests/resources/inject.html
Updates the displayed User-Agent string periodically. Ensure the HTML element with id 'u-a' exists to display the User-Agent.
```javascript
function updateUserAgent() { document.getElementById("u-a").textContent = navigator.userAgent; }
updateUserAgent();
window.setInterval(updateUserAgent, 1500);
```
--------------------------------
### Inject CSS into InAppBrowser
Source: https://github.com/apache/cordova-plugin-inappbrowser/blob/master/README.md
Injects CSS rules into the InAppBrowser window. This is useful for customizing the appearance of loaded web pages. Ensure the target is set to '_blank'.
```javascript
ref.insertCSS(details, callback);
```
--------------------------------
### Configure InAppBrowser Status Bar Style (iOS)
Source: https://github.com/apache/cordova-plugin-inappbrowser/blob/master/README.md
Set the text color style for the InAppBrowser's status bar on iOS using a config.xml preference. 'lightcontent' is for dark backgrounds, and 'darkcontent' (iOS 13+) is for light backgrounds.
```xml
```
--------------------------------
### InAppBrowser.hide
Source: https://github.com/apache/cordova-plugin-inappbrowser/blob/master/README.md
Hides the InAppBrowser window. This can be used to temporarily conceal the browser without closing it, for instance, while performing background operations or transitioning UI elements.
```APIDOC
## InAppBrowser.hide
### Description
Hides the `InAppBrowser` window. The browser remains in memory but is not visible to the user.
### Method Signature
`ref.hide();`
### Parameters
- __ref__: (InAppBrowser) - A reference to the `InAppBrowser` window.
### Example
```javascript
// Assuming 'browserRef' is a valid InAppBrowser reference
// browserRef.hide();
```
```
--------------------------------
### Update User Agent Display
Source: https://github.com/apache/cordova-plugin-inappbrowser/blob/master/tests/resources/local.html
This JavaScript function `updateUserAgent` retrieves the current user agent string from `navigator.userAgent` and updates the text content of an HTML element with the ID 'u-a'. The function is called once on load and then repeatedly every 1500 milliseconds using `window.setInterval` to keep the display current.
```javascript
function updateUserAgent() { document.getElementById("u-a").textContent = navigator.userAgent; } updateUserAgent(); window.setInterval(updateUserAgent, 1500);
```
--------------------------------
### Close InAppBrowser Window
Source: https://github.com/apache/cordova-plugin-inappbrowser/blob/master/README.md
Closes the InAppBrowser window. This method should be called on the reference obtained from `cordova.InAppBrowser.open()`.
```javascript
ref.close();
```
```javascript
var ref = cordova.InAppBrowser.open('https://apache.org', '_blank', 'location=yes');
ref.close();
```
--------------------------------
### InAppBrowser.close
Source: https://github.com/apache/cordova-plugin-inappbrowser/blob/master/README.md
Closes the InAppBrowser window. This method should be called when the user is finished interacting with the in-app browser or when it needs to be programmatically dismissed.
```APIDOC
## InAppBrowser.close
### Description
Closes the `InAppBrowser` window.
### Method Signature
`ref.close();`
### Parameters
- __ref__: (InAppBrowser) - A reference to the `InAppBrowser` window.
### Example
```javascript
// Assuming 'browserRef' is a valid InAppBrowser reference
// browserRef.close();
```
```
--------------------------------
### Hide InAppBrowser Window
Source: https://github.com/apache/cordova-plugin-inappbrowser/blob/master/README.md
Hides the InAppBrowser window. This method is useful for temporarily concealing the browser window without closing it. It is supported on Android and iOS.
```javascript
ref.hide();
```
```javascript
var ref = cordova.InAppBrowser.open('https://apache.org', '_blank');
// some time later...
ref.hide();
```
--------------------------------
### Remove InAppBrowser Event Listener
Source: https://github.com/apache/cordova-plugin-inappbrowser/blob/master/README.md
Removes a previously added event listener from the InAppBrowser window. This is only applicable when the InAppBrowser is opened with the target '_blank'. Ensure the event name and callback function exactly match those used when adding the listener.
```javascript
ref.removeEventListener(eventname, callback);
```
```javascript
var ref = cordova.InAppBrowser.open('https://apache.org', '_blank', 'location=yes');
var myCallback = function(event) { alert(event.url); }
ref.addEventListener('loadstart', myCallback);
ref.removeEventListener('loadstart', myCallback);
```
--------------------------------
### InAppBrowser.removeEventListener
Source: https://github.com/apache/cordova-plugin-inappbrowser/blob/master/README.md
Removes a listener for an event from the InAppBrowser. This method is only available when the target is set to '_blank'.
```APIDOC
## InAppBrowser.removeEventListener
### Description
Removes a listener for an event from the `InAppBrowser` window. This functionality is restricted to InAppBrowser windows opened with the target `'_blank'`.
### Method Signature
```javascript
ref.removeEventListener(eventname, callback);
```
### Parameters
- __ref__ (InAppBrowser) - Required - A reference to the `InAppBrowser` window.
- __eventname__ (String) - Required - The name of the event to stop listening for. Supported events include:
- `loadstart`: Fires when the `InAppBrowser` begins loading a URL.
- `loadstop`: Fires when the `InAppBrowser` completes loading a URL.
- `loaderror`: Fires when the `InAppBrowser` encounters an error while loading a URL.
- `exit`: Fires when the `InAppBrowser` window is closed.
- `message`: Fires when the `InAppBrowser` receives a message posted from the page loaded within it.
- `customscheme`: Fires when a link is followed that matches `AllowedSchemes`.
- `download`: (Android only) Fires when the `InAppBrowser` loads a URL that results in a file download.
- __callback__ (Function) - Required - The function to execute when the specified event fires. This function will receive an `InAppBrowserEvent` object as an argument.
### Supported Platforms
- Android
- Browser
- iOS
### Example
```javascript
var ref = cordova.InAppBrowser.open('https://apache.org', '_blank', 'location=yes');
var myCallback = function(event) { console.log(event.url); };
ref.addEventListener('loadstart', myCallback);
// To remove the listener:
ref.removeEventListener('loadstart', myCallback);
```
```
--------------------------------
### InAppBrowser.removeEventListener
Source: https://github.com/apache/cordova-plugin-inappbrowser/blob/master/README.md
Removes a previously added event listener from the InAppBrowser. This is crucial for preventing memory leaks and ensuring that callbacks are not triggered after they are no longer needed.
```APIDOC
## InAppBrowser.removeEventListener
### Description
Removes a listener for an event from the `InAppBrowser`. This is the counterpart to `addEventListener` and should be used to clean up listeners when they are no longer required.
### Method Signature
`ref.removeEventListener(eventname, callback);`
### Parameters
- __ref__: (InAppBrowser) - A reference to the `InAppBrowser` window.
- __eventname__: (String) - The name of the event whose listener should be removed.
- __callback__: (Function) - The specific callback function that was originally added as a listener and should now be removed.
### Example
```javascript
function handlePageLoadStart(event) {
console.log('Page loading started:', event.url);
}
// When opening the browser:
// let browserRef = cordova.InAppBrowser.open('https://example.com', '_blank');
// browserRef.addEventListener('loadstart', handlePageLoadStart);
// Later, to remove the listener:
// browserRef.removeEventListener('loadstart', handlePageLoadStart);
```
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.