Android Question WebView DOM storage: how to get access ?

peacemaker

Expert
Licensed User
Longtime User
HI, All

How to read variables from Session Storage ?
 

JohnC

Expert
Licensed User
Longtime User
ChatGPT generated these HTML pages to store a page count using various browser storage methods:
  • Session Storage - Only stores values for the current tab session - opening a new tab in the browser will clear values
  • Local Storage - Stores data between browser sessions
  • Cookie Storage - Stores data in browser cookie with expiration date
You could then use webviewextras.executeJavascript(wv, Javascript) to manipulate values from B4A using this ChatGPT generated example code:
B4X:
Sub Process_Globals
    Dim WebView1 As WebView
End Sub

Sub Globals
    Dim wvExtras As WebViewExtras
End Sub

Sub Activity_Create(FirstTime As Boolean)
    Activity.LoadLayout("layout")  ' Ensure this matches your layout file name
 
    WebView1.Initialize("WebView1")
    Activity.AddView(WebView1, 0, 0, 100%x, 100%y)
 
    wvExtras.Initialize(WebView1)
 
    ' Enable JavaScript in the WebView
    wvExtras.addJavascriptInterface(WebView1, "B4A")
 
    ' Load some initial HTML or a webpage
    WebView1.LoadUrl("https://www.example.com")
 
    ' Example: Writing to localStorage
    wvExtras.ExecuteJavascript("localStorage.setItem('key', 'value');")
 
    ' Example: Reading from localStorage
    Dim js As String
    js = "var value = localStorage.getItem('key'); B4A.CallSub('ProcessValue', value);"
    wvExtras.ExecuteJavascript(js)
End Sub

Sub WebView1_PageFinished (Url As String)
    ' Inject JavaScript here if you need to wait for the page to load
End Sub

' This Sub will be called from JavaScript
Sub ProcessValue(value As String)
    Log("Received value from localStorage: " & value)
End Sub

Notes:
  1. You might need to use wve.addWebChromeClient(wv, "WVE") to add chromeclient to the webview
  2. You might need to use WebViewSettings lib to do a wvs.setDOMStorageEnabled(wv,True) to enable DOM storage

Session Storage:
B4X:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Page View Counter</title>
</head>
<body>
    <h1>Page View Counter</h1>
    <p>Number of times you have visited this page: <span id="viewCount"></span></p>

    <script>
        // Check if there's already a count stored in session storage
        function getPageViews() {
            return sessionStorage.getItem('pageViews');
        }

        // Increment the page view count and store it in session storage
        function incrementPageViews() {
            let count = getPageViews();
            count = count ? parseInt(count) + 1 : 1;
            sessionStorage.setItem('pageViews', count);
            return count;
        }

        // Display the current count on the webpage
        function displayCount() {
            const count = incrementPageViews();
            document.getElementById('viewCount').textContent = count;
        }

        // Call the display function on page load
        window.onload = function() {
            displayCount();
        }
    </script>
</body>
</html>

Local Storage:
B4X:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Persistent Page View Counter</title>
</head>
<body>
    <h1>Persistent Page View Counter</h1>
    <p>Number of times you have visited this page: <span id="viewCount"></span></p>

    <script>
        // Check if there's already a count stored in local storage
        function getPageViews() {
            return localStorage.getItem('pageViews');
        }

        // Increment the page view count and store it in local storage
        function incrementPageViews() {
            let count = getPageViews();
            count = count ? parseInt(count) + 1 : 1;
            localStorage.setItem('pageViews', count);
            return count;
        }

        // Display the current count on the webpage
        function displayCount() {
            const count = incrementPageViews();
            document.getElementById('viewCount').textContent = count;
        }

        // Call the display function on page load
        window.onload = function() {
            displayCount();
        }
    </script>
</body>
</html>

Cookie Storage:
B4X:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cookie-based Page View Counter</title>
</head>
<body>
    <h1>Cookie-based Page View Counter</h1>
    <p>Number of times you have visited this page: <span id="viewCount"></span></p>

    <script>
        // Function to read a cookie value
        function getCookie(name) {
            let cookieArray = document.cookie.split(';');
            for(let i = 0; i < cookieArray.length; i++) {
                let cookiePair = cookieArray[i].split('=');
                if (name == cookiePair[0].trim()) {
                    return decodeURIComponent(cookiePair[1]);
                }
            }
            return null;
        }

        // Function to set a cookie
        function setCookie(name, value, daysToExpire) {
            const date = new Date();
            date.setTime(date.getTime() + (daysToExpire*24*60*60*1000));
            const expires = "expires=" + date.toUTCString();
            document.cookie = name + "=" + encodeURIComponent(value) + ";" + expires + ";path=/";
        }

        // Increment the page view count and store it in a cookie
        function incrementPageViews() {
            let count = getCookie('pageViews');
            count = count ? parseInt(count) + 1 : 1;
            setCookie('pageViews', count, 7); // Set cookie to expire in 7 days
            return count;
        }

        // Display the current count on the webpage
        function displayCount() {
            const count = incrementPageViews();
            document.getElementById('viewCount').textContent = count;
        }

        // Call the display function on page load
        window.onload = function() {
            displayCount();
        }
    </script>
</body>
</html>
 
Last edited:
Upvote 0

peacemaker

Expert
Licensed User
Longtime User
Ahhhh, just HTML was generated. I read like "B4A code was generated"... 😜
THanks !
 
Upvote 0

JohnC

Expert
Licensed User
Longtime User
Ahhhh, just HTML was generated. I read like "B4A code was generated"... 😜
THanks !
The sample B4A code was also generated by ChatGPT
 
Upvote 0

peacemaker

Expert
Licensed User
Longtime User
B4X:
js = "var value = localStorage.getItem('key'); B4A.CallSub('ProcessValue', false, value);"
or
js = "var value = localStorage.getItem('key'); B4A.CallSub('ProcessValue', true, value);"

 
Upvote 0
Top