Skip to content

Instantly share code, notes, and snippets.

@Pittan
Created August 10, 2017 14:47
Show Gist options
  • Save Pittan/61d007684aae68b40eefec7fedd72432 to your computer and use it in GitHub Desktop.
Save Pittan/61d007684aae68b40eefec7fedd72432 to your computer and use it in GitHub Desktop.
Make angular more compatible with iOS native webview
import { Injectable } from '@angular/core';
declare global {
interface Window {
WebViewJavascriptBridge: any;
WVJBCallbacks: any;
}
}
@Injectable()
export class NativeBridgeService {
private bridge: any = {};
constructor() {
// For development usage
this.bridge.callHandler = (name, data, responseCallback) => {
console.log('Native call:' + name, data);
};
this.bridge.registerHandler = (name, callback) => {
console.log('Register handler: ' + name);
};
this.setupWebViewJavascriptBridge(bridge => {
this.bridge = bridge;
// Tell native WebView that Angular is ready
bridge.callHandler('App Ready', {});
});
}
/**
* Call native WebView
* @param name
* @param data
* @param callback
*/
callHandler(name: string, data: any, callback?) {
this.bridge.callHandler(name, data, callback);
}
/**
* Register handler
* @param name
* @param callback
*/
registerHandler(name: string, callback) {
this.bridge.registerHandler(name, callback);
}
// from https://github.com/marcuswestin/WebViewJavascriptBridge
private setupWebViewJavascriptBridge(callback) {
if (Window.prototype.WebViewJavascriptBridge) { return callback(Window.prototype.WebViewJavascriptBridge); }
if (Window.prototype.WVJBCallbacks) { return window.WVJBCallbacks.push(callback); }
window.WVJBCallbacks = [callback];
const WVJBIframe = document.createElement('iframe');
WVJBIframe.style.display = 'none';
WVJBIframe.src = 'https://__bridge_loaded__';
document.documentElement.appendChild(WVJBIframe);
setTimeout(function() { document.documentElement.removeChild(WVJBIframe); }, 0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment