How do i execute javascript that was loaded from the DOM - vb.net

I am trying to execute a function in a javascript that has been loaded via the DOMDocument.
For instance:
'on page load
Webbrowser1.navigate("a htmldocument with a div called mainDiv")
Then later:
mDoc = WebBrowser1.Document
Dim mainDiv As IHTMLDOMNode = mDoc.DomDocument.getElementById("mainDiv")
mainDiv.innerHTML = (IO.File.ReadAllText("a file with just a div and script"))
'File has no html, head and body tags
So now i need to execute the script that was loaded retrospectively into mainDiv.
i've tried:
Webbrowser1.Document.InvokeScript("onLoadScript")
...but as far as i can gather, this method sees only the DOM loaded from the navigate event.
I'm hoping that there is a way of executing a script by accessing the DOMDocument.
Any help appreciated.
Thanks

You could try injecting a script that calls your dynamic script, dynamically. This bypasses the .InvokeScript function
HtmlElement headtag = WebBrowser1.Document.GetElementsByTagName("head")[0];
HtmlElement scripttag = WebBrowser1.Document.CreateElement("script");
IHTMLScriptElement scriptelm = (IHTMLScriptElement)scripttag.DomElement;
scriptelm.text = "onLoadScript();";
headtag.AppendChild(scripttag);

Related

VB.Net Webview2 How can I get html source code?

I sucessfully display a web site on WebView2 in my VB.net (Visual Studio 2017) project but can not get html souce code. Please advise me how to get html code.
My code:
Private Sub testbtn_Click(sender As Object, e As EventArgs) Handles testbtn.Click
WebView2.CoreWebView2.Navigate("https://www.microsoft.com/")
End Sub
Private Sub WebView2_NavigationCompleted(sender As Object, e As CoreWebView2NavigationCompletedEventArgs) Handles WebView2.NavigationCompleted
Dim html As String = ?????
End Sub
Thank you indeed for your advise in advance.
I've only just started messing with the WebView2 earlier today as well, and was just looking for this same thing. I did manage to scrape together this solution:
Dim html As String
html = Await WebView2.ExecuteScriptAsync("document.documentElement.outerHTML;")
' The Html comes back with unicode character codes, other escaped characters, and
' wrapped in double quotes, so I'm using this code to clean it up for what I'm doing.
html = Regex.Unescape(html)
html = html.Remove(0, 1)
html = html.Remove(html.Length - 1, 1)
Converted my code from C# to VB on the fly, so hopefully didn't miss any syntax errors.
Adding to #Xaviorq8 answer, you can use Span to get rid of generating new strings with Remove:
html = Regex.Unescape(html)
html = html.AsSpan()[1..^1].ToString();
I must credit #Xaviorq8; his answer was needed to solve my problem.
I was successfully using .NET WebBrowser and Html Agility Pack but I wanted to replace WebBrowser with .NET WebView2.
Snippet (working code with WebBrowser):
using HAP = HtmlAgilityPack;
HAP.HtmlDocument hapHtmlDocument = null;
hapHtmlDocument = new HAP.HtmlDocument();
hapHtmlDocument.Load(webBrowser1.DocumentStream);
HtmlNodeCollection nodes = hapHtmlDocument.DocumentNode.SelectNodes("//*[#id=\"apptAndReportsTbl\"]");
Snippet (failing code with WebView2):
using HAP = HtmlAgilityPack;
HAP.HtmlDocument hapHtmlDocument = null;
string html = await webView21.ExecuteScriptAsync("document.documentElement.outerHTML");
hapHtmlDocument = new HAP.HtmlDocument();
hapHtmlDocument.LoadHtml(html);
HtmlNodeCollection nodes = hapHtmlDocument.DocumentNode.SelectNodes("//*[#id=\"apptAndReportsTbl\"]");
Success withWebView2 and Html Agility Pack
using HAP = HtmlAgilityPack;
HAP.HtmlDocument hapHtmlDocument = null;
string html = await webView21.ExecuteScriptAsync("document.documentElement.outerHTML");
// thanks to #Xaviorq8 answer (next 3 lines)
html = Regex.Unescape(html);
html = html.Remove(0, 1);
html = html.Remove(html.Length - 1, 1);
hapHtmlDocument = new HAP.HtmlDocument();
hapHtmlDocument.LoadHtml(html);
HtmlNodeCollection nodes = hapHtmlDocument.DocumentNode.SelectNodes("//*[#id=\"apptAndReportsTbl\"]");
The accepted answer is on the right track. However, it's missing on important thing:
The returned string is NOT HTMLEncoded, it's JSON!
So to do it right, you need to deserialize the JSON, which is just as simple:
Dim html As String
html = Await WebView2.ExecuteScriptAsync("document.documentElement.outerHTML;")
html = Await JsonSerializer.DeserializeAsync(Of String)(html);

Parse a HTML string to DOM and return the DOM in the Express(node js) response

I wrote a javascript(nodejs+express) program to download a html document from a given url.
I converted into a DOM object using parse5, jsdom, cherrio(only one). Now I need to send the response(the DOM object) to an ajax call. But when I try
var document = jsdom(data); //can use any of these three
var $ = cheerio.load(data);
var document3 = parse5.parse(data);
return res.send({'data':document3});
It gives an error 'converting circular structure to json', which is obvious because I'm trying to convert a DOM object to JSON.
My requirement is to parse the HTML and send the DOM as response because I need to use the DOM on client side.
What should be approach?
Have you tried just send the DOM (assume you have done some process on it) as a string and convert the DOM string back to a DOM on client side? Obviously Json won't work for the DOM obj.

Getting HRESULT: 0x800A01B6 Exception while getting elements from InternetExplorerMedium website

I'm trying to make some code on VB.net that opens a website and logs in, and after that runs a report. Everything has been working fine when I try to get any of the from the website, but the ones that have this instruction within the OnClick property = "return oamSubmitForm('inputParamView:paramForm','inputParamView:paramForm:_idJsp106');"
Basically, if you see the following code, you see that I click on some of the CheckBoxes and it works just fine, but when I retrieve the button, it doesn't type an input, it actually has the link of the website when I use a whatc while debugging.
This is my code (I skipped the login section):
Private Sub open Page()
ieb = New SHDocVw.InternetExplorerMedium()
ieb.Navigate("http://example.example/qptheme2/pages/index.faces")
ieb.visible = True
ieb.Silent = True
While Not (ieb.ReadyState = WebBrowserReadyState.Complete)
Application.DoEvents()
End While
If v.checked = False Then
v.Click()
End If
v = ie.Document.GetElementById("inputParamView:paramForm:inputParametertuesday")
If v.checked = False Then
v.Click()
End If
v = ie.Document.GetElementById("inputParamView:paramForm:_idJsp106")
v.Click() '<-- IT FAILS HERE Exception HRESULT: 0x800A01B6
If I check the watch it shows mshtml.HTMLAnchorElementClass {http://example.example/qpreport/savedpages/savedReports.faces#}
if I check the source code from the page, this is the element that I'm trying to get:
<a id="inputParamView:paramForm:_idJsp106" onclick="return
oamSubmitForm('inputParamView:paramForm','inputParamView:paramForm:_idJsp106');" href="#"
I don't know if it has anything to do with the property OnClick.
I will appreciate any of your help trying to solve this issue.
I found the solution by myself. I just had to instance the element I was retrieving as mshtml.HTMLAnchorElementClass
after that, I was able to click on it.
Dim l As mshtml.HTMLAnchorElementClass = ieb.Document.GetElementById("inputParamView:paramForm:_idJsp106")
l.click()

Remotipart JS Not Executing

I have a form that needs to submit a .csv file to the server and then append the words in it to a textarea in my page. I am using Remotipart to upload the .csv using AJAX but I cannot get the javascript in the server response to execute. Here are the relevant parts of my code:
The Form:
=form_tag(upload_canvas_words_admin_page_widget_widget_instance_path(widget.page, widget),:method=>'post',:remote=>true,:multipart=>true,:class=>"upload_words_csv") do
= label_tag "Upload File"
= file_field_tag "file"
= submit_tag "Upload"
The Controller:
def upload_canvas_words
#csv_text = params[:file].read
end
The .js.haml file:
= remotipart_response do
- if remotipart_submitted?
alert('#{#csv_text}');
alert('!');
- else
alert('WHYYYYY?');
When I look at the response I see the javascript being wrapped in a bunch of html, which I assume has something to do with the iFrame transport. But the javascript never actually executes.
Refer this issue. And try to follow the solution given here.
https://github.com/JangoSteve/remotipart/issues/89
So what happens is that reponse arrives to the browser with html entity (like ") inside the textarea. When the js code for evaluation is extracted the html entities are replaced by theirs respective characters (like " to ').
That's a characteristic of a textarea. So it doesn't get executed
Adding data: {type: :script} to the form should be the fix

How to inject a javascript file in a Non-Local web page and invoke it

I'm using VB.NET 2008. I am building an application which had a webbrowser named "browser1". When I navigate a URL on it like "http://www.google.com" (not "file:///c:/test.html") it successfully loads the page. I am using the code to inject a javascript file in this page.
Dim mScript As HtmlElement
Dim mHead As HtmlElement
Dim jsPath As String
jsPath = (SoftwareROOT.Replace("\", "/")) & "/plugin.js"
With Browser1
mHead = Browser1.Document.GetElementsByTagName("head")(0)
mScript = .Document.CreateElement("script")
mScript.SetAttribute("type", "text/javascript")
mScript.SetAttribute("src", jsPath)
mHead.AppendChild(mScript)
.Document.InvokeScript("plugin_main")
End With
The code successfully creates the new element. But when it is trying to invoke script (the 2nd last line) then it fails to run the script.
Note:
File path is OK.
Code successfully works with a local page (like "c:\test.html").
"plugin_main" is a simple function of javascript alert().
You could run the script simply by navigating to it.
WebBrowser1.Navigate("javascript:code")