Reputation: 912
I have a webview and a Button (out of webview) in my layout. I want to know if there is any way to execute javascript code when i click in the button (using its OnClick event for example)
EDIT:
I have this HTML
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="PruebaAlert.js"></script>
</head>
<body>
<!--Your content here-->
</body>
</html>
I have my function JS in PruebaAlert.js
function myJSFunction(){
alert('hello, i was hit by Android button');
}
public class MainActivity extends Activity {
int pulsado = 0;
//Controla que estamos usando el layout web_view_not_visible
boolean web_view_not_visible = true;
TextView text;
Button button;
WebView myWebView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.web_view_not_visible);
myWebView = (WebView)findViewById(R.id.webview);
myWebView.loadUrl("file:///android_asset/StackOverflow.html");
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
if(true){
button = (Button)findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Log.d("WebView Debug" , "Entre en onClick()");
myWebView.loadUrl("javascript:myJSFunction()");
}
});
}
}
}
I click on Button (it is on bottom of the layout) but alert don't show. If i open HTML in Chrome or Firefox it's work fine
What happen?
Thanks!
Upvotes: 0
Views: 2685
Reputation: 13061
html
<html>
<head>
<script type="text/javascript">
function myJSFunction(){
alert('hello, i was hit by Android button');
}
</script>
//OR
<script type="text/javascript" src="yourJSFile.js"></script>
</head>
<body>
<!--Your content here-->
</body>
</html>
yourJSFile.js
function myJSFunction(){
alert('hello, i was hit by Android button');
}
onCreate
myWebView.loadUrl("yourHtml.html");
Then just call javascript when button is clicked:
myButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
myWebView.loadUrl("javascript:myJSFunction();");
}
});
Upvotes: 2
Reputation: 12176
You can call the javascript like this
myWebView.loadUrl("javascript:test('arguments')");
As for your second question that you asked in your comment.
Where do i put my javascript file?
There are two ways webview can load a page one loading a html page from the application and second pointing to external site. In both the cases the JS should be placed where the HTML will look for it.
Upvotes: 1