Expose variable to javascript context (Java / WebView)

时间:2018-12-03 13:19:19

标签: javascript java android android-webview

I want to expose a variable (a value) to the global javascript context. I don't want to expose an interface. I don't want to expose functions. I want to expose a single value in the global context of javascript, meaning that the value should be accessible with window.my_value;.

I tried overriding the onPageFinished method and running evaluateJavascript, but that seems to trigger way too late for my app to read the value (by the time the variable is set, my app is already running and has already read the undefined value of my_value).

Is there a way I can inject my variable, somehow, into the page I'm loading, as soon as possible, before any other JS has been loaded?

1 个答案:

答案 0 :(得分:-1)

Very simply

<script type="text/javascript">
    a = 100;
</script>

<script type="text/javascript">
    alert(a);
    // rest of your javascript code
</script>

There is no need for these to be in separate script tags, but for demonstration purposes, I'll leave those.

Unless there is some vital information missing from your question, this is fairly straightforward. As you say, you want this to be set before any of your other javascript is ran. Therefore, to achieve that, set the global variable before any of your other javascript is ran.