The WebView is providing incorrect window.innerHeight measurement

Having an issue with my Android app that uses WebView and JavaScript. In the onPageFinished() method of my WebViewClient, I trigger a JavaScript initializing function. However, when I try to access window.innerWidth in the JavaScript method, it always returns incorrect values (320 x 240) regardless of orientation. This is strange because elsewhere in the script, window.innerWidth and window.innerHeight give accurate numbers.

What's more confusing is that if I directly check the height and width of the WebView in onPageFinished(), using view.getHeight() and view.getWidth(), it gives me the correct values. This indicates that everything has loaded properly in WebView.

Any insights on what might be causing this discrepancy?

Appreciate any help!

Answer №1

The reason for this behavior is that JavaScript runs before the WebView's view-related setup takes place. This results in Android WebView providing a default value of 320x240 to JS. It is advisable to delay the execution of your JS code, like so:

function execute() {
    int height = view.getHeight();
    int width = view.getWidth();
};
window.setTimeout(execute, 300);

Answer №2

To ensure accuracy, I ultimately relied on the measurements retrieved from webView.getHeight() and webView.getWidth(), which were then adjusted for screen density before being passed as arguments to a javascript function using webView.loadUrl(). This approach provided me with the certainty that I was obtaining the correct values.

While following the suggestions in the preceding comments by verifying a width of 320 and a height of 240 may seem effective initially... it is important to note that this method may fail when executed on a device with those specific dimensions.

Answer №3

Upon further research, I have come across an alternative solution. In Java code, we can utilize the following:

new Handler().post(new Runnable(){ 
    @Override 
    public void run(){
        webview.loadUrl("...")
    }
}); 

By adding this to QueueMessage, and delaying the JavaScript execution, the desired outcome is achieved.

Answer №4

Here is an example of how I implemented this functionality:

C++ code in MainActivity:

webView.addJavascriptInterface(new WebAppInterface(this), "Android");

...

public class WebAppInterface {
    Context mContext;

    WebAppInterface(Context context) {
        mContext = context;
    }

    public int getWindowHeight() {
      return webView.getHeight();
    }
}

Javascript code:

var windowHeight = Android.getWindowHeight();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Get the ability to download numerous files simultaneously with pdfMake

Hello there, I am currently working with the pdfMake plugin in my Angular project. You can find the plugin here: https://github.com/bpampuch/pdfmake. I am facing a problem where I need to download multiple files with different document definitions. I have ...

The welcome message in Discord.js is displaying the user as a string of numbers instead of their real username

bot.on('guildMemberAdd', user =>{ const greetingMessage = new Discord.MessageEmbed() .setTitle(`Welcome to the server, ${user.user}! We're glad you've joined.`) const channel = user.guild.channels.cache.find(channel =&g ...

Include a link to a JavaScript file within a dynamically created HTML page in a Delphi VCL application

I am currently developing a Delphi XE5 VCL Forms Application which includes a TIdHTTPServer on the main form. Within this server, there is a CommandGet procedure called IdHTTPServer: procedure TForm1.IdHTTPServerCommandGet(AContext: TIdContext; ARequest ...

Update background to full screen and include text when hovering over DIV

Currently, I am utilizing Bootstrap and have a layout with 6 columns containing icons/text within. I desire to implement a hover effect where each column triggers a background change in transition for the entire section. In addition, text and button elemen ...

Testing the 'this' object in AngularJS

Currently, I am developing an application using AngularJs 1.4.4 and have recently started implementing Test-Driven Development (TDD) for the first time. I am utilizing Karma with Jasmine for testing and have encountered a challenge while trying to test an ...

Locate the timing, press, and exact coordinates of two touchpoints happening simultaneously

I am facing a unique dilemma that I cannot seem to solve. I want the user to perform a two-finger touch on the screen simultaneously, and I need to determine the coordinates and time duration of each touch event. Initially, I tried using the onTouchListen ...

What is the method for prompting a save as dialog in the browser in order to save JSON data stored in memory?

As the title suggests, I am looking for a way to store JSON data in memory. I want this action to be triggered by an onclick event on a DOM object. The goal is to save the data on the user's computer as if they were downloading a file. Saving it as t ...

jQuery slideDown() is taking precedence over the final element

I'm having trouble sliding a submenu dropdown on my mobile site. The last element is not moving out of the way as expected, and it's expanding over the current selector. Here is the code snippet: <li class="dropdown"> <a href="#">S ...

`Obtaining an array of selected values from a deeply nested JSON object`

Looking to extract specific key values from a nested JSON object based on the boolean value of another key. In this case, I need the "name" key values for items where the "checked" key is true, and return them in a result array. Here is an example of the ...

What criteria does Angular use to determine if a promise has been fulfilled?

Recently, I've delved into the realm of Angular promises for fetching data from a web service. One intriguing aspect that has caught my interest is how Angular somehow has the capability to determine whether a "request" has been successfully fulfilled ...

Issues have been reported with Firebase Authentication's createUserWithEmailAndPassword function specifically on physical devices when using a variable

There are two issues encountered when using the createUserWithEmailAndPassword method: The method works on the Emulator but fails in debug mode on a physical device Even though the email is saved into a variable, hardcoding a string for the email por ...

Using jQuery, identify when a key has been pressed within a three.js environment

How can I detect a keypress within a designated scene contained in a div with the id "world"? I've written the following code in an attempt to achieve this, but it doesn't seem to be working properly. Here is the code snippet: $('world&apos ...

Loading Animation with jQuery and Minimum Time Delay

Hello there, I am looking for a way to establish a minimum time duration for an onload function to ensure that a div is displayed for at least 2 seconds. Similar to setting a min-width or min-height, I want the div to be shown for a minimum of 2 seconds e ...

Looking to verify the validity of my email and phone number

Looking for some assistance in validating my email and telephone inputs for the contact form. The current code for email validation is incorrect, so I need help fixing it. It should be something like this: if(email.length == 0 || email.indexOf('@&apo ...

Sort arrays in Javascript by their respective lengths

Is there a way to arrange these arrays in descending order of the number of items they contain? I believe the logic is correct, but I might be missing some essential methods. The current output is empty. //Declare Variables var TN = ['Chattanooga&apo ...

Ways to retrieve the name of the class belonging to the data model within Angular

When working with this Angular data model code: export class Car { brand: string; year: number; nameOfModel() => { // Is there a way to retrieve the class name as a string: 'Car'? } } Is it possible to extract the class name in s ...

"Click-to-Submit Button Triggering Error Notification before Redirecting to New Page

I am looking to implement an error message for a button and then redirect the user to a specific URL. However, I am unsure of how to achieve this using JQuery as I am relatively new to it. The idea is that the user uploads a file and then clicks on the Sub ...

Is it possible to retrieve information from the parent in a Cloud Function?

How can I properly assign the name value inside the parent to a const? exports.myFunction = functions.database.ref('/messages/{pushId}/likes') .onWrite(event => { const name = event.parent.data.val().name; // This approach doesn't ...

How to implement dynamic color for classes in a v-for loop using Vue.js?

Struggling with a seemingly simple issue that may be easy for VueJS pros. In my data, I have JSON objects with an attribute that can take values of 10, 20, 30, or 40. Depending on this value, I want to change the color of a v-btn. I've attempted mul ...

Navigating through intricate HTML structures with JavaScript can be challenging

Snippet of 01.js code: var childElements = document.getElementById('selected-plays').getElementsByTagName('li'); function getRequiredElements(childElements) { var listItems = []; var i = 0; for(i = 0 ; i < childElements. ...