I am trying to use peerjs in android vie webview, but the problem is it not working, when I debugged and tried different approaches I got to know that normal js functions work with no problem, the problem only when I call a function which includes peerjs
permissions i took in manifest file
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
MAINACTIVITY
here are two buttons 1 calls to simple js function named callJs and other one calls peerjs function named testweb
public class MainActivity extends AppCompatActivity {
@SuppressLint("JavascriptInterface")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView webView = findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
// Setting Allowed JS Bullet Window
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.setWebChromeClient(new WebChromeClient(){
@Override
public void onPermissionRequest(PermissionRequest request) {
request.grant(request.getResources());
}
});
webView.addJavascriptInterface(new JavaScriptInterface(this),"AndroidFunction");
webView.loadUrl("file:///android_asset/webViewTest.html");
Button webTest1 = findViewById(R.id.webTest1);
//calls normal js function
webTest1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
webView.post(new Runnable() {
@Override
public void run() {
webView.evaluateJavascript("javascript:callJS()", new ValueCallback<String>() {
@Override
public void onReceiveValue(String value) {
}
});
}
});
}
});
Button webTest2 = findViewById(R.id.webTest2);
//calls js function with peerjs
webTest2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
webView.post(new Runnable() {
@Override
public void run() {
webView.evaluateJavascript("javascript:testWeb()", new ValueCallback<String>() {
@Override
public void onReceiveValue(String value) {
}
});
}
});
}
});
}
JAVASCRIPTINTERFACE
public class JavaScriptInterface {
MainActivity mainActivity;
public JavaScriptInterface(MainActivity mainActivity) {
this.mainActivity = mainActivity;
}
@JavascriptInterface
public void showToast(String toast){
Toast.makeText(mainActivity, toast, Toast.LENGTH_LONG).show();
}
js functions
<script src="./peerjs.js"></script>
<script type="text/javascript">
function callJS() {
AndroidFunction.showToast("Toast From javascript");
alert("Android Called JS Of callJS Method");
}
function testWeb() {
alert("testWeb Method called");
var peer = new Peer(1234, {
host: "192.168.****",
port: 8000,
path: "/strange",
});
peer.on("open", () => {
AndroidFunction.showToast("Toast From testWebPeer");
});
}
</script>