I am using WebKit browser control in my WPF application. I am using it because I want to rendered Protovis enabled HTML on it. Till this point I am successful. Now, I want to pass some parameters specially arrays of double, int and strings to one of the Java script method of the rendered page within the control. I tried InvokeScriptMethod() API from WebKit but it did not work for me if I want to pass parameter(s). Everything works well if I invoke the script method which doesn't take any parameter.
Can somebody help me? I am desperate for it.:)
Thanks,
Omkar
I get HRESULT as E_FAIL if I don't wait until the site is fully loaded.
You have to wait until this event:
private void webKitBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
object[] arr = {"some parameter"};
String returned = webKitBrowser1.Document.InvokeScriptMethod("JavascriptFunctionName", arr) as String;
}
is fired. After that, everything worked fine for me.
You can use,
webKitBrowser1.StringByEvaluatingJavaScriptFromString("javascript:YourMethod();");
Related
NOT using API
I am currently attempting to use a web browser in C# to load google maps and automatically focus on my current location, however, for some reason I cannot get this to work properly. The idea is simple. Load Google maps, and either execute the script to focus on my current location:
mapBrowser.Document.InvokeScript("mylocation.onButtonClick");
Or, invoke the button click through an HtmlElement:
HtmlElement myLocationButton = mapBrowser.Document.GetElementById("mylocation");
myLocationButton.InvokeMember("click");
But, of course neither of these methods actually work correctly, the coordinates returned are incorrent and the map never actually focuses. Any ideas on how I can fix this issue properly? The scripts aren't invoked until after the document is actually loaded:
private void mapBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if(mapBrowser.Url.ToString() == "https://www.google.com/maps/preview/")
{
try
{
//HtmlElement myLocationButton = mapBrowser.Document.GetElementById("mylocation");
//myLocationButton.InvokeMember("click");
mapBrowser.Document.InvokeScript("mylocation.onButtonClick");
//mapBrowser.Document.InvokeScript("focus:mylocation.main");
}
catch (Exception ex)
{
MessageBox.Show("Error Invoking Script: " + ex.Message);
}
}
}
so I don't believe that is the cause of my problem. Even more frustratingly, the auto-focus works fine if I click the button manually.
Any help is appreciated, thank you!
(NOTE, you may have to go into IE and allow Google maps access to your location in order to replicate this issue properly)
I've had problem few times that WebBrowser control uses too old version of IE. You need to modify registry to get it to use newer version of IE.
I tried "https://www.google.com/maps/preview/" with both IE 8 and 9 and it gave me an error, but it works on IE 10.
See: http://weblog.west-wind.com/posts/2011/May/21/Web-Browser-Control-Specifying-the-IE-Version
I am new to building windows 8 apps using C#.
Whenever I navigate to a page I get a pop-up saying "no apps are installed to open this type of link ms-resource". However, the app runs fine.
The code that I use to navigate to ScenarioPage from MainPage is:
private void HyperlinkButton_Click_1(object sender, RoutedEventArgs e)//code from MSDN
{
this.Frame.Navigate(typeof(ScenarioPage));
}
Can someone please help me or provide some pointers on how to remove the pop-up.
Instead of passing a type, you need to pass an object. From the linked MSDN page example:
// Navigate to object using the Navigate method
this.Navigate(new HomePage());
So in your case it would be
this.Frame.Navigate(new ScenarioPage());
OR, you can use the override that takes an Uri parameter.
this.Frame.Navigate(new Uri("ScenarioPage.xaml", UriKind.Relative));
You can't have your cake and eat it too, apparently.
I'm currently using the System.Windows.Forms.WebBrowser in my application. The program currently depends on using the GetElementsByTagName function. I use it to gather up all the elements of a certain type (either "input"s or "textarea"s), so I can sort through them and return the value of a specific one. This is the code for that function (my WebBrowser is named web1):
// returns the value from a element.
public String FetchValue(String strTagType, String strName)
{
HtmlElementCollection elems;
HtmlDocument page = web1.Document.Window.Frames[1].Document;
elems = page.GetElementsByTagName(strTagType);
foreach (HtmlElement elem in elems)
{
if (elem.GetAttribute("name") == strName ||
elem.GetAttribute("ref") == strName)
{
if (elem.GetAttribute("value") != null)
{
return elem.GetAttribute("value");
}
}
}
return null;
}
(points to note: the webpage I need to pull from is in a frame, and depending on circumstances, the element's identifying name will be either in the name or the ref attribute)
All of that works like a dream with the System.Windows.Forms.WebBrowser.
But what it is unable to do, is redirect the opening of a new window to remain in the application. Anything that opens in a new window shoots to the user's default browser, thus losing the session. This functionality can be easily fixed with the NewWindow2 event, which System.Windows.Forms.WebBrowser doesn't have.
Now forgive me for being stunned at its absence. I have but recently ditched VB6 and moved on to C# (yes VB6, apparently I am employed under a rock), and in VB6, the WebBrowser possessed both the GetElementsByTagName function and the NewWindow2 event.
The AxSHDocVw.WebBrowser has a NewWindow2 event. It would be more than happy to help me route my new windows to where I need them. The code to do this in THAT WebBrowser is (frmNewWindow being a simple form containing only another WebBrowser called web2 (Dock set to Fill)):
private void web1_NewWindow2(
object sender,
AxSHDocVw.DWebBrowserEvents2_NewWindow2Event e)
{
frmNewWindow frmNW = new frmNewWindow();
e.ppDisp = frmNW.web2.Application;
frmNW.web2.RegisterAsBrowser = true;
frmNW.Visible = true;
}
I am unable to produce on my own a way to replicate that function with the underwhelming regular NewWindow event.
I am also unable to figure out how to replicate the FetchValue function I detailed above using the AxSHDocVw.WebBrowser. It appears to go about things in a totally different way and all my knowledge of how to do things is useless.
I know I'm a sick, twisted man for this bizarre fantasy of using these two things in a single application. But can you find it in your heart to help this foolish idealist?
I could no longer rely on the workaround, and had to abandon System.Windows.Forms.WebBrowser. I needed NewWindow2.
I eventually figured out how to accomplish what I needed with the AxWebBrowser. My original post was asking for either a solution for NewWindow2 on the System.Windows.Forms.WebBrowser, or an AxWebBrowser replacement for .GetElementsByTagName. The replacement requires about 4x as much code, but gets the job done. I thought it would be prudent to post my solution, for later Googlers with the same quandary. (also in case there's a better way to have done this)
IHTMLDocument2 webpage = (IHTMLDocument2)webbrowser.Document;
IHTMLFramesCollection2 allframes = webpage.frames;
IHTMLWindow2 targetframe = (IHTMLWindow2)allframes.item("name of target frame");
webpage = (IHTMLDocument2)targetframe.document;
IHTMLElementCollection elements = webpage.all.tags("target tagtype");
foreach (IHTMLElement element in elements)
{
if (elem.getAttribute("name") == strTargetElementName)
{
return element.getAttribute("value");
}
}
The webbrowser.Document is cast into an IHTMLDocument2, then the IHTMLDocument2's frames are put into a IHTMLFramesCollection2, then I cast the specific desired frame into an IHTMLWindow2 (you can choose frame by index # or name), then I cast the frame's .Document member into an IHTMLDocument2 (the originally used one, for convenience sake). From there, the IHTMLDocument2's .all.tags() method is functionally identical to the old WebBrowser.Document.GetElementsByTagName() method, except it requires an IHTMLElementCollection versus an HTMLElementCollection. Then, you can foreach the collection, the individual elements needing to be IHTMLElement, and use .getAttribute to retrieve the attributes. Note that the g is lowercase.
The WebBrowser control can handle the NewWindow event so that new popup windows will be opened in the WebBrowser.
private void webBrowser1_NewWindow(object sender, CancelEventArgs e)
{
// navigate current window to the url
webBrowser1.Navigate(webBrowser1.StatusText);
// cancel the new window opening
e.Cancel = true;
}
http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/361b6655-3145-4371-b92c-051c223518f2/
The only solution to this I have seen was a good few years ago now, called csExWb2, now on Google code here.
It gives you an ExWebBrowser control, but with full-on access to all the interfaces and events offered by IE. I used it to get deep and dirty control of elements in a winforms-hosted html editor.
It may be a bit of a leap jumping straight into that, mind.
I am automating a task using webbrowser control , the site display pages using frames.
My issue is i get to a point , where i can see the webpage loaded properly on the webbrowser control ,but when it gets into the code and i see the html i see nothing.
I have seen other examples here too , but all of those do no return all the browser html.
What i get by using this:
HtmlWindow frame = webBrowser1.Document.Window.Frames[1];
string str = frame.Document.Body.OuterHtml;
Is just :
The main frame tag with attributes like SRC tag etc, is there any way how to handle this?Because as i can see the webpage completely loaded why do i not see the html?AS when i do that on the internet explorer i do see the pages source once loaded why not here?
ADDITIONAL INFO
There are two frames on the page :
i use this to as above:
HtmlWindow frame = webBrowser1.Document.Window.Frames[0];
string str = frame.Document.Body.OuterHtml;
And i get the correct HTMl for the first frame but for the second one i only see:
<FRAMESET frameSpacing=1 border=1 borderColor=#ffffff frameBorder=0 rows=29,*><FRAME title="Edit Search" marginHeight=0 src="http://web2.westlaw.com/result/dctopnavigation.aspx?rs=WLW12.01&ss=CXT&cnt=DOC&fcl=True&cfid=1&method=TNC&service=Search&fn=_top&sskey=CLID_SSSA49266105122&db=AK-CS&fmqv=s&srch=TRUE&origin=Search&vr=2.0&cxt=RL&rlt=CLID_QRYRLT803076105122&query=%22LAND+USE%22&mt=Westlaw&rlti=1&n=1&rp=%2fsearch%2fdefault.wl&rltdb=CLID_DB72585895122&eq=search&scxt=WL&sv=Split" frameBorder=0 name=TopNav marginWidth=0 scrolling=no><FRAME title="Main Document" marginHeight=0 src="http://web2.westlaw.com/result/dccontent.aspx?rs=WLW12.01&ss=CXT&cnt=DOC&fcl=True&cfid=1&method=TNC&service=Search&fn=_top&sskey=CLID_SSSA49266105122&db=AK-CS&fmqv=s&srch=TRUE&origin=Search&vr=2.0&cxt=RL&rlt=CLID_QRYRLT803076105122&query=%22LAND+USE%22&mt=Westlaw&rlti=1&n=1&rp=%2fsearch%2fdefault.wl&rltdb=CLID_DB72585895122&eq=search&scxt=WL&sv=Split" frameBorder=0 borderColor=#ffffff name=content marginWidth=0><NOFRAMES></NOFRAMES></FRAMESET>
UPDATE
The two url of the frames are as follows :
Frame1 whose html i see
http://web2.westlaw.com/nav/NavBar.aspx?RS=WLW12.01&VR=2.0&SV=Split&FN=_top&MT=Westlaw&MST=
Frame2 whose html i do not see:
http://web2.westlaw.com/result/result.aspx?RP=/Search/default.wl&action=Search&CFID=1&DB=AK%2DCS&EQ=search&fmqv=s&Method=TNC&origin=Search&Query=%22LAND+USE%22&RLT=CLID%5FQRYRLT302424536122&RLTDB=CLID%5FDB6558157526122&Service=Search&SRCH=TRUE&SSKey=CLID%5FSSSA648523536122&RS=WLW12.01&VR=2.0&SV=Split&FN=_top&MT=Westlaw&MST=
And the properties of the second frame whose html i do not get are in the picture below:
Thank you
I paid for the solution of the question above and it works 100 %.
What i did was use this function below and it returned me the count to the tag i was seeking which i could not find :S.. Use this to call the function listed below:
FillFrame(webBrowser1.Document.Window.Frames);
private void FillFrame(HtmlWindowCollection hwc)
{
if (hwc == null) return;
foreach (HtmlWindow hw in hwc)
{
HtmlElement getSpanid = hw.Document.GetElementById("mDisplayCiteList_ctl00_mResultCountLabel");
if (getSpanid != null)
{
doccount = getSpanid.InnerText.Replace("Documents", "").Replace("Document", "").Trim();
break;
}
if (hw.Frames.Count > 0) FillFrame(hw.Frames);
}
}
Hope it helps people .
Thank you
For taking html you have to do it that way:
WebClient client = new WebClient();
string html = client.DownloadString(#"http://stackoverflow.com");
That's an example of course, you can change the address.
By the way, you need using System.Net;
This works just fine...gets BODY element with all inner elements:
Somewhere in your Form code:
wb.Url = new Uri("http://stackoverflow.com");
wb.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(wbDocumentCompleted);
And here is wbDocumentCompleted:
void wb1DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
var yourBodyHtml = wb.Document.Body.OuterHtml;
}
wb is System.Windows.Forms.WebBrowser
UPDATE:
The same as for the document, I think that your second frame is not loaded at the time you check for it's content...You can try solutions from this link. You will have to wait for your frames to be loaded in order to see its content.
The most likely reason is that frame index 0 has the same domain name as the main/parent page, while the frame index 1 has a different domain name. Am I correct?
This creates a cross-frame security issue, and the WB control just leaves you high and dry and doesn't tell you what on earth went wrong, and just leaves your objects, properties and data empty (will say "No Variables" in the watch window when you try to expand the object).
The only thing you can access in this situation is pretty much the URL and iFrame properties, but nothing inside the iFrame.
Of course, there are ways to overcome teh cross-frame security issues - but they are not built into the WebBrowser control, and they are external solutions, depending on which WB control you are using (as in, .NET version or pre .NET version).
Let me know if I have correctly identified your problem, and if so, if you would like me to tell you about the solution tailored to your setup & instance of the WB control.
UPDATE: I have noticed that you're doing a .getElementByTagName("HTML")(0).outerHTML to get the HTML, all you need to do is call this on the document object, or the .body object and that should do it. MyDoc.Body.innerHTML should get the the content you want. Also, notice that there are additional iFrames inside these documents, in case that is of relevance. Can you give us the main document URL that has these two URL's in it so we / I can replicate what you're doing here? Also, not sure why you are using DomElement but you should just cast it to the native object it wants to be cast to, either a IHTMLDocument2 or the object you see in the watch window, which I think is IHTMLFrameElement (if i recall correctly, but you will know what i mean once you see it). If you are trying to use an XML object, this could be the reason why you aren't able to get the HTML content, change the object declaration and casting if there is one, and give it a go & let us know :). Now I'm curious too :).
I'm relatively new to Javascript, and although I know how to use it, I don't really understand the mechanics behind it. Bear with me here.
I need to write a small app that creates a chart (in SVG) based on data I take in as an XML file. I found PlotKit, which does exactly what I need, except that it's written in Javascript, while my current program is written in c#. I did some googling and found a few articles which explain how to evaluate simple Javascript code using the .NET VsaEngine class. Unfortunately, I have absolutely no idea how to use the VsaEngine to execute more complicated Javascript that requires references to other files. Basically, all I want is for c# to be able to call something like this as Javascript:
var layout = new PlotKit.Layout("bar", {});
layout.addDataset("data", [[0, 0], [1, 1], [2, 2]]);
layout.evaluate();
var canvas = MochiKit.DOM.getElement("graph");
var plotter = new PlotKit.SVGRenderer(canvas, layout, {});
var svg = SVGRenderer.SVG();
And get back the SVG string for the chart. I have no idea how to make it so that the above script knows where to look for all of the necessary objects. If I were to make a web page to do this, I would just add a few script headers referencing /plotkit/Layout.js, /plotkit/Canvas.js, etc., the Javascript would work fine.
If anyone could explain exactly how I would use PlotKit through C#, or could explain a more effective way to do this, I would really appreciate it.
EDIT: I realize I wasn't too clear with this question - I need my c# program to emulate a Javascript engine and use the PlotKit library without actually running a web browser. Is there any way to do this?
PlotKit is a JavaScript library that is intended to execute in the Client's Web Browser. C# is executed on the Server. To go about communicating between the two, you would render whatever data you wish to pass to PlotKit on the server and then output it in the HTML you send to the client.
So in your C# codebehind you would construct the JSON object that would be passed to PlotKit's addDataset method.
...
public partial class Default : System.Web.UI.Page
{
protected string PlotKitData = "[]";
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack) PlotKitData = GenerateJSON();
...
Then in your ASPX codefront you would have something like this.
<script>
var layout = new PlotKit.Layout("bar", {});
layout.addDataset("data", <%=PlotKitData%>);
layout.evaluate();
var canvas = MochiKit.DOM.getElement("graph");
var plotter = new PlotKit.SVGRenderer(canvas, layout, {});
var svg = SVGRenderer.SVG();
</script>
Perhaps ZedGraph might suit your needs instead?