调用从Android活动的JavaScript函数函数、Android、JavaScript

2023-09-06 03:43:51 作者:你抢走了我的一切。

我正在使用的主要活动如下code,它使功能显示()没有定义

I am using the following code in the main activity , its giving the function display() is not defined

public class cordovaExample extends DroidGap {
    Context mcontext;
    private novel n;
    private Server s;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new Thread(new Server(this)).start();
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) { }
        new Thread(new Client()).start();

        super.init();

        n = new novel(this, appView); 
        s = new Server(this,appView);

        appView.getSettings().setJavaScriptEnabled(true);
        appView.addJavascriptInterface(n, "novel");
        appView.addJavascriptInterface(s, "Server");

        super.loadUrl("file:///android_asset/www/index.html");
        super.loadUrl("javascript:display()");
    }
}

在最后一行它给人错误显示()没有定义

At the last line it giving the error display() is not defined

function display() {
    alert("abc");
}

以上code显示了显示功能,这是我使用的HTML文件

Above code shows the display function which is I am using in the html file

任何形式的帮助将AP preciated

Any type of help will be appreciated

推荐答案

这是一个坏主意,让科尔多瓦负载的JavaScript在页面加载。这应该由当地的JavaScript处理。试着打电话给你的显示器()函数,这样在HTML页面本身:

It's a bad idea to make Cordova load JavaScript on page load. This should be handled by your local JavaScript. Try to call your display() function like this in the HTML page itself:

<script>
    function display()
    {


        alert("abc");


    }

    window.onload = function() {
        display();
    }
</script>

如果您需要调用一个JavaScript从内部科尔多瓦在以后的任何一点上,它可以这样做是这样的:

If you need to call a JavaScript from within Cordova at any later point, it is possible to do so this way:

sendJavascript("display();");

要由其他类访问这个方法,你将需要访问您的主要活动。最简单的,但是,也许是不安全的方法是创建一个在您的主要活动一个静态变量,将举行活动本身。例如:

To access this method from other classes, you will need to access your main activity. The easy-but-perhaps-unsafe method is to create a static variable in your main Activity that will hold the activity itself. Example:

public class MyActivity extends DroidGap {
    public static MyActivity activity;

    public void onCreate(Bundle savedInstanceState) {
        activity = this;
    }
}

然后,从你的类的任何地方,做的:

Then, from anywhere in your classes, do:

MyActivity.activity.sendJavascript('display();');