Modify HTML in a Internet Explorer window using external.menuArguments - vb.net

I've got a VB.NET class that is invoked with a context menu extension in Internet Explorer.
The code has access to the object model of the page, and reading data is not a problem. This is the code of a test function...it changes the status bar text (OK), prints the page HTML (OK), changes the HTML by adding a text and prints again the page HTML (OK, in the second pop-up my added text is in the HTML)
But the Internet Explorer window doesn't show it. Where am I doing wrong?
Public Sub CallingTest(ByRef Source As Object)
Dim D As mshtml.HTMLDocument = Source.document
Source.status = "Working..."
Dim H As String = D.documentElement.innerHTML()
MsgBox(H)
D.documentElement.insertAdjacentText("beforeEnd", "ThisIsATest")
H = D.documentElement.outerHTML()
MsgBox(H)
Source.status = ""
End Sub
The function is called like this from JavaScript:
<script>
var EB = new ActiveXObject("MyObject.MyClass");
EB.CallingTest(external.menuArguments);
</script>

To the best of my understanding, in order to use insertAdjacentText or any of the other editing methods, the document object should be in the design mode.
In design mode you can edit the document freely, and so can the user.
Check this site for more details

I do not think that Alex is right, something else is the matter.
When I tried to do something like that, insertBefore would not work for me, but appendChild worked just fine, so adding an element is possible.
I worked in Javascript, but I don't expect that makes a difference.

Related

CefSharp SetZoomLevel not working

I am using in a WinForm an object of type:
CefSharp.WinForms.ChromiumWebBrowser
Everything is working fine but I am having an issue when I try to change the ZoomLevel with SetZoomLevel method:
If oBrowser.IsBrowserInitialized Then
oBrowser.SetZoomLevel(-2.0)
Dim frame As CefSharp.IFrame = oBrowser.GetMainFrame
Dim request As CefSharp.IRequest = frame.CreateRequest()
request.Url = url
request.Method = "POST"
request.InitializePostData()
Dim element = request.PostData.CreatePostDataElement()
element.Bytes = postDataBytes
request.PostData.AddElement(element)
request.Headers = headers
frame.LoadRequest(request)
End If
The first time I open the WinForm the Zoom level doesn't change, while it works correctly from the 2nd refresh.
Am I missing some initialization and/or method call... Or do I have to call this method in another position?
Note: the CEFSharp DLL version is 63.0.3.0.
The .NET Framework is 4.5.2
EDITED 01.06.2018: I've found a solution (see below) but now there's another problem: the zoom change is made when the browser is already visible, so it's not nice for the final user to see the page size changing during the form load.
Has anyone a suggestion to freeze the layout during zoom change? Please note that .SuspendLayout() and .ResumeLayout() are not working.
I've found a way to answer my own question. I post it here as it could be useful to other users.
You must add a LoadingStateChanged handler to the ChromiumWebBrowser object:
AddHandler oBrowser.LoadingStateChanged, AddressOf WebBrowserOnLoadingStateChanged
The method would be then something like:
Private Sub WebBrowserOnLoadingStateChanged(ByVal sender As Object, ByVal loadingStateChangedEventArgs As LoadingStateChangedEventArgs)
Dim oBrowser As WinForms.ChromiumWebBrowser = CType(sender, WinForms.ChromiumWebBrowser)
If Not oBrowser.IsLoading Then
oBrowser.SetZoomLevel(-2.0)
End If
End Sub
This solution works good in my environment but now there's another problem: the zoom change is made when the browser is already visible, so it's not nice for the final user to see the Zoom Level changing during the form load.

Can HTAs be used to automate web browsing?

I am new to HTAs. I just read https://msdn.microsoft.com/en-us/library/ms536496%28v=vs.85%29.aspx and am a bit confused.
Can I use HTAs to automate browsing? Say I want to download a web page and fill in a form automatically, i.e. from a script. How would an HTA help me do this, if at all? It's important that the JavaScript code in the downloaded page is run as usual. I should be able to enter somehow and fill in the form after it has finished initializing, just as if I were a human agent.
First, you need to open an IE window, as follows:
var IE = new ActiveXObject("InternetExplorer.Application");
Then navigate the IE window to the webpage you want:
IE.Navigate("www.example.com");
Wether your IE window is visible or invisible, it's up to you. Use Visible property to make it visible:
IE.Visible = true;
Then, you should wait until the webpage is completely loaded and then run a function that takes your desired actions. To do so, first, get the HTML document object from the webpage using Document property of IE object, then repeatedly check the readyState property of document object. In the code below, it is assumed that you have a function named myFunc, which takes your desired actions on the webpage. (For example, modifying the contents of the webpage.)
var doc = IE.Document;
interval = setInterval(function() {
try
{
if (doc.readyState == "complete")
{
myFunc();
clearInterval(interval);
}
}
catch (e) {}
}, 1000);
In the function myFunc, you can do anything you want with the webpage since you have HTML document object stored in doc variable. You can also use parentWindow property to get the HTML window object.

Looking for a specific tag

I had a previous question regarding a way to access a proxy card from within a web page when using Chrome. I'm now attempting to instead use a vb.Net application with an embedded CefSharp object. I have the code I need to access the proxy card (thanks to Smart Card API), but I need an easy way to indicate that this is even an option. My thought is to:
Put an otherwise empty element on the web page (such as <div id='smartcard' />)
Inside Visual Basic, monitor the contents of the page for this <div />
If the <div /> is found, make sure the card reader is detected. If so, add some text (and maybe an image) to its contents indicating the the card can be scanned
Once a card scan is detected, put the value from the card into a form element and POST it
It seems likely to me that I'm going to have to use some combination of JavaScript and vb.net code, but I'm so new to CefSharp that I really have no idea where to start.
Thanks in advance for all your help.
Not being a C# programmer, I looked at the information on the General Usage guide many times and still didn't really understand it. That said, I think I've been able to get this project off the ground. In addition to the CefSharp project, I'm also using the non-free Smart Card API from CardWerk.
Below is some snippets of what I did.
VB.Net
Imports CefSharp
Imports Subsembly ' For the SmartCard namespace
Class MainWindow
Private WithEvents CardManager As SmartCard.CardTerminalManager
Private Sub MainWindow_Initialized(sender As Object, e As EventArgs) Handles Me.Initialized
browser.Address = "https://jake-dev7.local/trainingmatrix/"
Debug.Print(SmartCard.SMARTCARDAPI.API_VERSION)
CardManager = SmartCard.CardTerminalManager.Singleton
CardManager.Startup(True)
End Sub
Private Sub browser_LoadingStateChanged(sender As Object, e As LoadingStateChangedEventArgs) Handles browser.LoadingStateChanged
Dim script As String
If Not e.IsLoading Then
If CardManager.SlotCount Then
script = "if ($('#proxcard').length) { proxcard_init() }"
browser.GetMainFrame().ExecuteJavaScriptAsync(script)
End If
End If
End Sub
Protected Sub InsertedEvent(ByVal aSender As Object, ByVal aEventArgs As SmartCard.CardTerminalEventArgs) Handles CardManager.CardInsertedEvent
Dim aCard As SmartCard.CardHandle
Dim nActivationResult As SmartCard.CardActivationResult
Dim iFacilityCode As Integer
Dim iCardID As Integer
' There's a bunch of code here taken from the sample code that came
' with the SmartCard API from CardWerk to pull the facility code and
' card id out of the prox card.
If iFacilityCode <> 0 And iCardID <> 0 Then
Dim script As String
script = "if ($('#proxcard').length) { proxcard_scan(" & iFacilityCode & ", " & iCardID & ") }"
browser.GetMainFrame().ExecuteJavaScriptAsync(script)
End If
End Sub
End Class
JavaScript
(This is in a .js file that is loaded by the web page. This page can also be loaded in Chrome, Firefox, IE, etc and these functions will never be run which keeps this utility usable for computers that don't have the custom .exe and card reader).
// These proxcard_* functions are called via our parent application
// (CefSharp object embeded in a vb.Net assembly)
function proxcard_init() {
$('#proxcard').html("<div class='or'>- OR -</div><div><img src='proxcard.jpg'><br>Scan your card</div>");
}
function proxcard_scan(facilityID, cardID) {
var vars = {
facilityID: facilityID,
cardID: cardID
};
if ($('form#adduser').length) {
// We're on the add user page. Check to see if this card matches somebody.
$.post('httprequest.php?type=get-emp-from-prox', vars, function(data) {
if (data && data.number) {
// Update UI and backend form fields. If everything validates, submit the form
} else {
// Clear UI and backend form fields that pertain to user ID
alert('Card not found');
}
}, 'json');
} else if ($('form#update').length) {
// Deal with the update form
}
}
In my actual code, I have multiple else if statements for dealing with different forms where I allow a card to be scanned. They are not included to keep this from getting out of hand :).
Please Note: This is not intended to be the entire project or all the code needed to process prox cards using CefSharp. My hope is that it will be enough to help somebody else.

Web browser control, modal window/popup to STAY INSIDE web browser control for Visual Studio 2015/Visual Basic 2015

this is the first time I'm posting a question here; I have searched and searched and searched here and other places and I cannot seem to get any results. I'm using VISUAL BASIC 2015 in Visual Studio 2015. QUESTION: I need to have a modal window/popup from a particular website remain INSIDE the web browser control/window on my form (WebBrowser1); when a particular link is clicked, the modal window/popup jumps out of the form and directly to the user on their screen. I have to keep this popup inside because there are other links to be clicked on that popup, but if it jumps out of the web browser control, no code will work since it's outside WebBrowser1. What I have found is code for older versions, and not 2015; if anything I can even add WebBrowser2 to have the popups/modal windows appear there if possible, just as long as I can code them to keep clicking inside the form. PLEASE HELP! THANK YOU!
window.open (and a click on <a target="_blank"> etc) can be handled via the NewWindow2 event. Hans already pointed out how to do that in comments. NewWindow3 works too, but need at least Windows XP SP2.
As for window.showModalDialog, it is a bit tricky. IE has IDispatchEx (wrapped as IExpando in .Net) implemented on scripting objects so you replace the methods and properties with your own implementation. But window.showModalDialog shows a dialog that has arguments and return values, you need to override those properties in the modal dialog you create too. The code looks roughly like tis:
void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
//skip events from frames
if(WebBrowserReadyState.Complete!=webBrowser1.ReadyState) return;
if(FindLoginFormOnPage()) {DoLogin();return;}
if(IsWelcomePage()){NavigateToPage1();return;}
if(IsPage1()){SubmitFormOnPage1();return;}
if(IsPage1FormResult()){
var document=webBrowser1.Document.DomDocument as mshtml.ITMLDocument2;
var expando =(IExpando)document.parentWindow;
expando.RemoveMember(expando.GetMethod("showModalDialog"
,BindingFlags.Instance | BindingFlags.Public);
expando.AddMethod("showModalDialog"
,new ShowModalDialogDelegate(this.MyShowModalDialog));
}
......
}
object MyShowModalDialog(string url, object varArgIn, object options)
{
using(FromMyShowModalDialog myShowModalDialog
=new MyShowModalDialog())
{
myShowModalDialog.StartupUrl=url;
myShowModalDialog.DialogArguments=varArgIn;
//omit the code to parse options
//and set dialog height/width/topleft location etc
if(myShowModalDialog.ShowDialog()==DialogResult.OK)
{
//do something on the return value before passing to the scripts
......
return myShowModalDialog.ReturnValue;
}
return null;
}
}
and in the Load event handler of MyShowModalDialog you call something like webBrowser1.Navigate to show the page requested by the parent page.
Now you need to pass the arguments to the webbrowser control on the new form. Do the same as above but replace another property this time.
expando.RemoveProperty("dialogArguments");
expando.AddProperty("dialogArguments")
.SetValue(expando,this.DialogArguments);
This will let the web page access the value passed from MyShowModalDialog and stored in this.DialogArguments.
The earliest you can access the DOM is in webBrowser1_DocumentCompleted. By that time the scipts on the page that read window.dialogArguments are probably already executed and got nothing. After overriding window.dialogArguments, you need to study the script on the page to find out how to revert that. for example, if the page has
<head>
<script>
var oMyObject = window.dialogArguments;
var sFirstName = oMyObject.firstName;
var sLastName = oMyObject.lastName;
</script>
...
<span style="color: 00ff7f">
<script>
document.write(sFirstName);
</script>
</span>
you need to change the values of sFirstName and sLastName then change the innerText property of the span, probably identify via its relationship with a named div or table cell. You can write the necessary changes in a script and call it via HtmlDocument.InvokeScript.
If the page returns a value to its parent, you need to pass it on to your parent form too. Override window.returnValue so when the script writes to window.returnValue it writes to a variable you provided
......
expando.RemoveProperty("returnValue");
expando.AddProperty("returnValue").SetValue(expando,this.ReturnValue);

How do I copy a DOM sub tree between two webbrowser.HmtlDocuments?

A WinForm application. I want to scrape a part of an HTML web page and save it into a local html file.
I have one local file, "empty.htm" (containing just "I'm empty" in the body), one remote web page, and two WebBrowser controls. WebBrowser1 navigates to the remote page, WebBrowser2 to the local file. Both display their content appropriately.
Now I try:
string rootIDToCopy = "InterestingDivID";
HtmlDocument htmlDocument = webBrowser1.Document;
HtmlElement rootElementToCopy =
htmlDocument.GetElementById(rootIDToCopy);
if (rootElementToCopy != null)
{
HtmlDocument dest = webBrowser2.Document;
if (dest != null)
{
HtmlElement destBody = dest.Body; // Point 1
destBody.AppendChild(rootElementToCopy); // Point 2
}
}
Now, when I'm in Point 1, I see that destBody exists, has no children and has an InnerHTML of "I'm empty". rootElementToCopy appears valid (has three children and an ok InnerHtml). However, at Point 2 I get "Value does not fail within the expected range" (probably from Windows.Forms.UnsafeNativeMethods.IHTMLElement2.InsertAdjacentElement).
Help will be appreciated!
You may not be allowed to: see WRONG_DOCUMENT_ERR and ownerDocument in the DOM specification.
Instead I think you might have to serialize the subtree to a flat string format before you try to insert it into a different document.