Run Javascript Function as soon as CefWebBrowser is Ready (VB.Net)

1,437 views
Skip to first unread message

Luis Valle

unread,
Jan 31, 2013, 6:09:24 PM1/31/13
to cef...@googlegroups.com
I have successfully managed to get Cefglue (version 3) running under VB.Net but I need your help.

I am loading a local html file and what I am trying to do is execute a Javascript function as soon as the browser is ready to receive calls. I have tried using the property "IsAccessible" but nothing happens. Is there another property I can use to accomplish this?

I know my code works because I can call the same Javascript function from a button on my Windows Form.

Here is my code:

Imports System.Threading
Imports Xilium.CefGlue
Imports Xilium.CefGlue.WindowsForms
Imports Xilium.CefGlue.CefSettings
Imports System.IO

Public Class Form1
    Dim browserCtl As CefWebBrowser = Nothing

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        createBrowser()
        loadBrowser()

        Do Until browserCtl.IsAccessible
            Application.DoEvents()

        Loop
        browserCtl.Browser.GetMainFrame.ExecuteJavaScript("myTestInject()", Nothing, 0)

    End Sub

    Private Sub Form1_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        Try
            If Environment.OSVersion.Version.Major < 6 Then
                Process.GetCurrentProcess().Kill()
            End If
        Catch ex As Exception

        End Try
    End Sub

    Private Sub createBrowser()
        Xilium.CefGlue.CefRuntime.Load()
        Dim mainArgs = New Xilium.CefGlue.CefMainArgs(New String() {})
       
        Dim cefSettings = New Xilium.CefGlue.CefSettings
        With cefSettings
            .SingleProcess = True
            .MultiThreadedMessageLoop = True
            .LogSeverity = Xilium.CefGlue.CefLogSeverity.Verbose
            .LogFile = "C:\CefGlue.log"
        End With

        Xilium.CefGlue.CefRuntime.Initialize(mainArgs, cefSettings, Nothing)
    End Sub

    Private Sub loadBrowser()
        If Debugger.IsAttached Then
            If IO.Directory.Exists("C:\Documents and Settings\u60lev00\My Documents\Visual Studio 2010\Projects\TRAIN Safe\TRAIN Safe\src") Then
                Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory("C:\Documents and Settings\u60lev00\My Documents\Visual Studio 2010\Projects\TRAIN Safe\TRAIN Safe\src", Application.StartupPath & "\src", True)
                Application.DoEvents()
            End If
        End If

        browserCtl = New CefWebBrowser
        browserCtl.Dock = DockStyle.Fill
        browserCtl.BringToFront()

        browserCtl.StartUrl = Application.StartupPath & "\src\handler.htm"
       
        Me.Controls.Add(browserCtl)
        browserCtl.CreateControl()
    End Sub

    Private Sub btnJS_Click(sender As System.Object, e As System.EventArgs) Handles btnJS.Click
        browserCtl.Browser.GetMainFrame.ExecuteJavaScript("callFromWinForm('Im in.')", Nothing, 0)
    End Sub

End Class

Dmitry Azaraev

unread,
Feb 1, 2013, 3:38:21 AM2/1/13
to cef...@googlegroups.com
You need to wait when document loaded inside browser window. For this purposes you can use CefLoadHandler. OnLoadStart/OnLoadEnd/OnLoadError methods. And search at ceforum - this theme already discussed many times, and different solutions available. Main idea - you can fire event from OnLoadEnd.



--
You received this message because you are subscribed to the Google Groups "CefGlue" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cefglue+u...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
 
 



--
Best regards,
   Dmitry

Luis Valle

unread,
Feb 3, 2013, 7:47:53 PM2/3/13
to cef...@googlegroups.com, dmitry....@gmail.com
I couldn't get CefLoadHandler to work, so I ended up using Ajax to send a message to my Windows app and it works wonders.

If anybody wants me to post my code I will. Let me know...

Wladimir Coka

unread,
Feb 4, 2013, 3:11:57 AM2/4/13
to cef...@googlegroups.com, dmitry....@gmail.com
Hi Luis, I'd like you to post your code to see how to comunicate to Windows app

Thanks

Luis Valle

unread,
Feb 4, 2013, 6:20:57 PM2/4/13
to cef...@googlegroups.com, dmitry....@gmail.com
HERE YOU GO...


    Imports System.Threading
    Imports Xilium.CefGlue
    Imports Xilium.CefGlue.WindowsForms
    Imports Xilium.CefGlue.CefSettings
    Imports System.IO

    Public Class Form1
        Public Shared browserCtl As CefWebBrowser = Nothing


        Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
            createBrowser()
            loadBrowser()
        End Sub

        Private Sub Form1_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
            Try
                If Environment.OSVersion.Version.Major < 6 Then
                    Process.GetCurrentProcess().Kill()
                End If
            Catch ex As Exception

            End Try
        End Sub

        Private Sub createBrowser()
            Xilium.CefGlue.CefRuntime.Load()
            Dim mainArgs = New Xilium.CefGlue.CefMainArgs(New String() {})
          
            Dim cefSettings = New Xilium.CefGlue.CefSettings
            With cefSettings
                .SingleProcess = True
                .MultiThreadedMessageLoop = True
                .LogSeverity = Xilium.CefGlue.CefLogSeverity.Verbose
                .LogFile = "C:\CefGlue.log"
            End With

            Xilium.CefGlue.CefRuntime.Initialize(mainArgs, cefSettings, Nothing)
        CefRuntime.RegisterSchemeHandlerFactory("http", "", New schemeFactory())

        End Sub

        Private Sub loadBrowser()
            If Debugger.IsAttached Then
                If IO.Directory.Exists("C:\Documents and Settings\u60lev00\My Documents\Visual Studio 2010\Projects\TRAIN Safe\TRAIN Safe\src") Then
                    Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory("C:\Documents and Settings\u60lev00\My Documents\Visual Studio 2010\Projects\TRAIN Safe\TRAIN Safe\src", Application.StartupPath & "\src", True)
                    Application.DoEvents()
                End If
            End If

            browserCtl = New CefWebBrowser
            browserCtl.Dock = DockStyle.Fill
            browserCtl.BringToFront()

            browserCtl.StartUrl = Application.StartupPath & "\src\handler.htm"
          
            Me.Controls.Add(browserCtl)
            browserCtl.CreateControl()
        End Sub

        Private Sub btnJS_Click(sender As System.Object, e As System.EventArgs) Handles btnJS.Click
            browserCtl.Browser.GetMainFrame.ExecuteJavaScript("callFromWinForm('Im in.')", Nothing, 0)
        End Sub

    End Class

    Public Class schemeHandler
    Inherits CefResourceHandler

    Protected Overrides Function ProcessRequest(request As CefRequest, callback As CefCallback) As Boolean
        Dim inCom As String() = request.Url.ToString.Split("~")
        Dim xClass = inCom(1)

        If xClass = "DOMComplete" Then
            JSComm.OnLoadEnd()
        ElseIf xClass = "btnJS" Then
            JSComm.OnLoadEnd()
        ElseIf xClass = "EXITAPP" Then
            JSComm.EXITCommand()
        ElseIf xClass = "INTRODONE" Then
            JSComm.checkforNewCourseFiles()
        End If

        callback.Continue()
        Return (True)
    End Function

    Protected Overrides Sub GetResponseHeaders(response As CefResponse, ByRef responseLength As Long, ByRef redirectUrl As String)
    End Sub

    Protected Overrides Function ReadResponse(response As System.IO.Stream, bytesToRead As Integer, ByRef bytesRead As Integer, callback As CefCallback) As Boolean
        Return (False)
    End Function

    Protected Overrides Function CanGetCookie(cookie As CefCookie) As Boolean
        Return False
    End Function

    Protected Overrides Function CanSetCookie(cookie As CefCookie) As Boolean
        Return False
    End Function

    Protected Overrides Sub Cancel()
    End Sub
End Class

Public Class schemeFactory
    Inherits CefSchemeHandlerFactory
    Protected Overrides Function Create(browser As CefBrowser, frame As CefFrame, schemeName As String, request As CefRequest) As CefResourceHandler
        Return New schemeHandler()
    End Function
End Class


'''My html file is setup like this:

        var xmlhttp;
            function ajaxFunction() {
                xmlhttp = new XMLHttpRequest();
            }

            function sendMessageToWindows(whatM) {
                whatM = whatM.replace(/&/g, '--NN--');
                //alert(whatM);
                xmlhttp.open("GET", "http://fromJS/~" + whatM, true);
                xmlhttp.send(null);               
            }

            function callFromWinForm(winMsg) {
                var zp = winMsg.split('~');
                //alert(winMsg);
                if (zp[0] == 'DNLDNEW') {
                    showProgNewCourse(zp[1]);
                } else if (zp[0] == 'HIDEDLD') {
                    hideProgCourse();
                }
                //if (winMsg.match(',')) {
                    //var sp = winMsg.split(',');
                //}
                //alert(winMsg);
            }


'''Then I have a VB Class file called JSComm with the following:

Imports System.IO

Public Class JSComm
    Public Shared Sub answerTest()
        MsgBox("It works")
    End Sub

    Public Shared Sub OnLoadEnd()
        TRAIN_Safe.Form1.browserCtl.Browser.GetMainFrame.ExecuteJavaScript("callFromWinForm('welcome to TRAIN Safe')", Nothing, 0)
    End Sub

    Public Shared Sub EXITCommand()
        Application.Exit()
    End Sub

    Public Shared Sub checkforNewCourseFiles()
        'TRAIN_Safe.Form1.browserCtl.Browser.GetMainFrame.ExecuteJavaScript("callFromWinForm('Other Stuff')", Nothing, 0)
    End Sub
End Class






Look at my javascript and then look at the ProcessRequest Function to get a sense of how I am doing this...
Reply all
Reply to author
Forward
0 new messages