Created
August 10, 2017 14:47
-
-
Save Pittan/61d007684aae68b40eefec7fedd72432 to your computer and use it in GitHub Desktop.
Make angular more compatible with iOS native webview
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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