0

I have app using android webview. I tried to call javascript from Java. I have the line below which I expect to display hello world but webview goes blank.

webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);

webView.loadUrl("javascript:document.write('hello world')");

Is my code correct or I missed something?

Displaying using document.write is for testing purposes only for calling JS function.

2 Answers 2

2

First change the string to "hello world" from "hello" :-)

I tried this and it is working

Activity

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        WebView webView = (WebView) findViewById(R.id.webView1);
        webView.getSettings().setJavaScriptEnabled(true);

        webView.loadUrl("javascript:document.write('hello world')");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

XML

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >


    <WebView
        android:id="@+id/webView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>
Sign up to request clarification or add additional context in comments.

1 Comment

Hi, I've tried your answer but without success .. can you help me with my question please? stackoverflow.com/questions/42633793/…
0
    Try this way

wview.loadUrl("file:///android_asset/index.html");

    **index.html**
copy index.html in assests folder

 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Insert title here</title>
    </head>
    <body>
    <h1>Hello World</h1>
    </body>
    </html>

2 Comments

i used document.write to write hello world for testing purposes only. The requirement is to call JS function not just displaying hello world.
wat's ur requirement can u eloberate

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.