import android.webkit.WebView;import android.webkit.WebSettings;import android.webkit.WebViewClient;import android.webkit.WebChromeClient;
<uses-permission android:name="android.permission.INTERNET"/><application android:usesCleartextTraffic="true">...</application>
<WebViewandroid:id="@+id/webview"android:layout_height="match_parent"android:layout_width="match_parent"/>
import android.webkit.JavascriptInterface;public class JsBridge {@JavascriptInterfacepublic void getData(String data) {System.out.println(data);}}
public class MainActivity extends AppCompatActivity {private WebView webview;private WebSettings webSettings;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);initView();}private void initView() {webview = (WebView) findViewById(R.id.webview);webSettings = webview.getSettings();webSettings.setUseWideViewPort(true);webSettings.setLoadWithOverviewMode(true);// Disable cachewebSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);webview.setWebViewClient(new WebViewClient(){@Overridepublic boolean shouldOverrideUrlLoading(WebView view, String url) {view.loadUrl(url);return true;}});// Enable jswebSettings.setJavaScriptEnabled(true);webview.addJavascriptInterface(new JsBridge(), "jsBridge");// Or load a local html file (webView.loadUrl("file:///android_asset/xxx.html"))webview.loadUrl("https://x.x.x/x/");}}
#import <WebKit/WebKit.h>
-(WKWebView *)webView{if(_webView == nil){// Create a webpage configuration objectWKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];// Create a settings objectWKPreferences *preference = [[WKPreferences alloc]init];// Set "Whether javaScript is supported". The value is YES by default.preference.javaScriptEnabled = YES;// Set "Allow javaScript to open a window without user interaction". In iOS, the value is set to NO by default.preference.javaScriptCanOpenWindowsAutomatically = YES;config.preferences = preference;// This class is used to manage interactions between native and JavaScript.WKUserContentController * wkUController = [[WKUserContentController alloc] init];// Register a js method with the name jsToOcNoPrams. Set objects to handle and receive the JS method.[wkUController addScriptMessageHandler:self name:@"jsToOcNoPrams"];[wkUController addScriptMessageHandler:self name:@"jsToOcWithPrams"];config.userContentController = wkUController;_webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) configuration:config];// UI delegate_webView.UIDelegate = self;// Navigation delegate_webView.navigationDelegate = self;// Webpage to be renderedNSString *path = [[NSBundle mainBundle] pathForResource:@"JStoOC.html" ofType:nil];NSString *htmlString = [[NSString alloc]initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];[_webView loadHTMLString:htmlString baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];}return _webView;}[self.view addSubview:self.webView];
// Called when the page starts to load-(void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {}// Called when the page fails to load-(void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {[self.progressView setProgress:0.0f animated:NO];}// Called when content starts to be returned-(void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {}// Called when the page finishes loading-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {[self getCookie];}// Called when a submission error occurs-(void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {[self.progressView setProgress:0.0f animated:NO];}// Called after receiving the server's redirect request, i.e., when the service is redirected-(void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation {}
<p style="text-align:center"> <button id="btn2" type = "button" onclick = "jsToOcFunction()"> Call OC with parameters with JS </button> </p>function jsToOcFunction(){window.webkit.messageHandlers.jsToOcWithPrams.postMessage({"params":"res.randstr"});}
-(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{// message.body is the json data passed to the client// Use message.body to obtain the parameter body passed with JSNSDictionary * parameter = message.body;// Call OC with JSif([message.name isEqualToString:@"jsToOcWithPrams"]){// The client obtains the data passed with js and performs operations on the dataparameter[@"params"]}}
Was this page helpful?