Android Question JavaScript injection before the page loading

Mattiaf

Active Member
Licensed User
I am using the UltimateWebView library in my B4A project and trying to inject JavaScript into a specific webpage before it fully loads. I implemented the ShouldInterceptRequest method to check the URL and inject the JavaScript, but it seems that the injection doesn't occur as expected, actually it doesn't occur at all!

Here is my code snippet:
B4X:
Private Sub UltimateWebView1_ShouldInterceptRequest(Request As WebResourceRequest) As WebResourceResponse
    If Request.url.Contains("my website address") Then
        Dim Javascript As String = "(function(){ let a = window.setTimeout; let b = window.setInterval; window.setTimeout = function(f, t) { if (t < 10000) a(f, t); else console.log(f, t); }; window.setInterval = function(f, t) { if (t < 10000) b(f, t); else console.log(f, t); } }());"
        
        UltimateWebView1.EvaluateJavascript(Javascript)
        Log("JavaScript injected before the page loading")
    End If
    
    Return Null ' Allow the page to load
End Sub

Is there a specific way to ensure that the JavaScript gets injected before the page starts loading? Any insights or suggestions would be appreciated!
This is the full code

B4X:
Sub Class_Globals
    Private Root As B4XView
    Private xui As XUI
    Private txtUrl As EditText
    Public UltimateWebView1 As UltimateWebView
    Private WebChromeClient As UltimateWebChromeClient

    Private fp As FileProvider
End Sub

Public Sub Initialize

End Sub


Private Sub B4XPage_Created (Root1 As B4XView)
    Root = Root1
    Root.LoadLayout("MainPage")
    Dim URL As String = $"
my website address
"$
    
    txtUrl.Text = URL
    fp.Initialize

    
    WebChromeClient.Initialize2("UltimateWebView1",UltimateWebView1).AllowFullScreenVideo(True,False) 'AllowFullScreenVideo only if you need, it is not necessary to set.

    
    UltimateWebView1.Settings.AllowContentAccess=True
    UltimateWebView1.Settings.BuiltInZoomControls=False
    UltimateWebView1.Settings.JavaScriptEnabled=True
    UltimateWebView1.Settings.DomStorageEnabled=True
    UltimateWebView1.Settings.JavaScriptCanOpenWindowsAutomatically=False
    UltimateWebView1.Settings.MediaPlaybackRequiresUserGesture=False
    UltimateWebView1.Settings.SaveFormData=True
    UltimateWebView1.CookieManager.AcceptCookies=True
    UltimateWebView1.CookieManager.AcceptFileSchemeCookies=True
    UltimateWebView1.CookieManager.AcceptThirdPartyCookies=True

End Sub

Private Sub btnGo_Click
    UltimateWebView1.LoadUrl(txtUrl.Text)
End Sub
Private Sub UltimateWebView1_ShouldInterceptRequest(Request As WebResourceRequest) As WebResourceResponse
    ' Controlla l'URL della richiesta per determinare se vuoi iniettare il codice
    If Request.url.Contains("https://whipwhip") Then ' Sostituisci con l'URL della pagina da caricare
        ' JavaScript da iniettare
        Dim Javascript As String = "(function(){ let a = window.setTimeout; let b = window.setInterval; window.setTimeout = function(f, t) { if (t < 10000) a(f, t); else console.log(f, t); }; window.setInterval = function(f, t) { if (t < 10000) b(f, t); else console.log(f, t); } }());"

        ' Inietta il codice JavaScript nella pagina
        UltimateWebView1.EvaluateJavascript(Javascript)
        Log("JavaScript iniettato prima del caricamento della pagina")
    End If

    Return Null ' Permetti il caricamento della pagina
End Sub

Sub UltimateWebView1_EvaluateJavascriptResult(res As String)
    Log("Result: " & res)
End Sub

Private Sub UltimateWebView1_OverrideUrl (Request As WebResourceRequest) As Boolean
    ' Estrai l'URL dalla richiesta
    Dim url As String = Request.Url

    ' Log dell'URL per debug
    Log("OverrideUrl = " & url)

    ' Verifica se l'URL inizia con "https://whipwhip"
    If url.StartsWith("https://whipwhip") Then
        ' Se l'URL è valido, consenti la navigazione
        Log("Navigazione consentita per: " & url)
        Return False
    Else
        ' Se l'URL non è valido, blocca la navigazione
        Log("Navigazione bloccata per: " & url)
        Return True
    End If
End Sub

Private Sub UltimateWebView1_CreateWindow (OverridenRequest As WebResourceRequest, ChildWebView As WebView, IsDialog As Boolean, IsUserGesture As Boolean) As Boolean
    ' Estrai l'URL dalla richiesta
    Dim url As String = OverridenRequest.Url

    ' Log dell'URL per debug
    Log("CreateWindow URL = " & url)

    ' Verifica se l'URL inizia con "https://whipwhip"
    If url.StartsWith("https://whipwhip") Then
        ' Se l'URL è valido, consenti la creazione della nuova finestra
        Log("Navigazione consentita per: " & url)
        Return True ' Consenti la nuova finestra
    Else
        ' Se l'URL non è valido, blocca la creazione della nuova finestra
        Log("Popup bloccato per: " & url)
        Return False ' Impedisci la nuova finestra
    End If
End Sub
 

drgottjr

Expert
Licensed User
Longtime User
1) call a method (using javascriptinterface) which executes in b4a as the last statement when you executejavascript. since it's the last statement, if it runs, then you can know your script has been injected.
2) remember: you are executing javascript within an empty context, so if you're defining variables or assigning values, they will be lost.
3) i have no idea how ultimatewebview works, but i would assume both javascriptinterface and executejavascript are available. using regular webview + regular webviewextras, it works like this:


B4X:
...
    wvx.executeJavascript(webview, "alert('hello,sailor!');B4A.CallSub('info',false, 'INJECTED, BABY!');")
    webview.LoadUrl("https://www.b4x.com")


Sub info(message As String)
    Log("message from client: " & message)
End Sub

Sub webview_PageFinished (Url As String)
    Log("Page loaded")
End Sub

tested. works. when run, you will note that the injected javascript runs before the page loads (a message in b4a confirms this). after that, the page loads (you will see confirmation of loading AFTER the injected javascript runs.
 

Attachments

  • inject1.png
    8.6 KB · Views: 50
  • inject2.png
    46.9 KB · Views: 49
  • inject3.png
    21.6 KB · Views: 49
Reactions: byz
Upvote 0

kofiking

Member
Inject JavaScript here, WebkitWebView1_LoadResource:
Private Sub WebkitWebView1_LoadResource (Url As String) 'Works from API level 1 and above.
    
    ' Inject JavaScript here'
    


End Sub
 
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…