编程语言
首页 > 编程语言> > c# – 在WebBrowser控件中修改Javascript变量

c# – 在WebBrowser控件中修改Javascript变量

作者:互联网

我有一个访问过的网页,使用以下内容声明一个名为date的变量:

var date=new Date("03 Oct 2013 16:04:19");

然后该日期显示在页面顶部.有没有办法让我修改那个日期变量? (而不仅仅是可见的HTML源代码)

我一直在尝试使用InvokeScript,但我觉得很难掌握,如果有人知道并且可以发布一些与此直接相关的例子,我将非常感激.谢谢.

解决方法:

您可以使用JavaScript的eval注入任何JavaScript代码,它适用于任何IE版本.您需要确保该网页至少有一个< script>标签,但这很容易:

Public Class Form1

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Call WebBrowser1.Navigate("http://example.com")
    End Sub

    Private Sub WebBrowser1_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
        '
        ' use WebBrowser1.Document.InvokeScript to inject script
        '
        ' make sure the page has at least one script element, so eval works
        WebBrowser1.Document.Body.AppendChild(WebBrowser1.Document.CreateElement("script"))
        WebBrowser1.Document.InvokeScript("eval", New [Object]() {"(function() { window.newDate=new Date('03 Oct 2013 16:04:19'); })()"})
        Dim result As String = WebBrowser1.Document.InvokeScript("eval", New [Object]() {"(function() { return window.newDate.toString(); })()"})
        MessageBox.Show(result)

    End Sub

End Class

或者,您可以使用VB.NET后期绑定直接调用eval,而不是Document.InvokeScript,这可能更容易编码和读取:

Public Class Form1

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Call WebBrowser1.Navigate("http://example.com")
    End Sub

    Private Sub WebBrowser1_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted

        '
        ' use VB late binding to call eval directly (seamlessly provided by.NET DLR)
        '
        Dim htmlDocument = WebBrowser1.Document.DomDocument
        Dim htmlWindow = htmlDocument.parentWindow
        ' make sure the page has at least one script element, so eval works
        htmlDocument.body.appendChild(htmlDocument.createElement("script"))
        htmlWindow.eval("var anotherDate = new Date('04 Oct 2013 16:04:19').toString()")
        MessageBox.Show(htmlWindow.anotherDate)
        ' the above shows we don't have to use JavaScript anonymous function,
        ' but it's always a good coding style to do so, to scope the context:
        htmlWindow.eval("window.createNewDate = function(){ return new Date().toString(); }")
        MessageBox.Show(htmlWindow.eval("window.createNewDate()"))

        ' we can also mix late binding and InvokeScript
        MessageBox.Show(WebBrowser1.Document.InvokeScript("createNewDate"))

    End Sub

End Class

标签:javascript,vb-net,webbrowser-control,c-2
来源: https://codeday.me/bug/20190831/1775887.html