How to find the position of an element in a web browser?

I have a web browser control form that loads a web page (its working fine, the page loads fine)

Now my problem is that I want to find whether a specific URL link is below the fold or above the fold (I mean, should the user scroll down to see this link or not) is this v visible without scrolling or we need to scroll to see it. I hope I understand.

I did an advanced search, but it looks like the location information of the html elements (above or below the current view) is not available.

Does anyone know something about this and can point me in the right direction, please? (I'm looking for a C # solution - WinForms)

Update : Many thanks to John Kerner for the code. Carefully evaluate the time and effort that he put into solving my problem.

And Jonathan and everyone else. I would like to note that Jonathan also answered as an answer, but he only allows one answer to be marked as an answer. His comment was also a clear and helpful hint. Damn you guys are great!

+6
source share
2 answers

Ok, I tested this on google and stackoverflow and it works:

private bool isElementVisible(WebBrowser web, string elementID) { var element = web.Document.All[elementID]; if (element == null) throw new ArgumentException(elementID + " did not return an object from the webbrowser"); // Calculate the offset of the element, all the way up through the parent nodes var parent = element.OffsetParent; int xoff = element.OffsetRectangle.X; int yoff = element.OffsetRectangle.Y; while (parent != null) { xoff += parent.OffsetRectangle.X; yoff += parent.OffsetRectangle.Y; parent = parent.OffsetParent; } // Get the scrollbar offsets int scrollBarYPosition = web.Document.GetElementsByTagName("HTML")[0].ScrollTop; int scrollBarXPosition = web.Document.GetElementsByTagName("HTML")[0].ScrollLeft; // Calculate the visible page space Rectangle visibleWindow = new Rectangle(scrollBarXPosition, scrollBarYPosition, web.Width, web.Height); // Calculate the visible area of the element Rectangle elementWindow = new Rectangle(xoff,yoff,element.ClientRectangle.Width, element.ClientRectangle.Height); if (visibleWindow.IntersectsWith(elementWindow)) { return true; } else { return false; } } 

Then, to use it, you simply call:

 isElementVisible(webBrowser1, "topbar") //StackOverflow top navigation bar 
+7
source

I have an idea that could work (never tried, but this is the best I can offer you, sorry)

You can call javascripts functions in webbrowsercontrol: LINK

You can also create javascripts functions that give you the position of an element: LINK

If you mix these two concepts, you can know if the element is visible or not, since you know the size of the webbrowser control.

Please note that you can enter javascript code in webbrowsercontrol. This SO post explains how to do this: LINK

Good luck.

+3
source

Source: https://habr.com/ru/post/908079/


All Articles