问题
Having a C# WebBrowser control inside my WinForms application, and being aware of the Navigating event, I never came up with a nice and elegant solution to the following:
- If a user actively navigates to another URL, I want to allow it.
- If the page redirects "on its own" to another URL, I want to cancel it.
For case 1 there are some cases I can think of:
- User clicks an
atag and thehrefattribute is evaluated to load another URL. - User clicks on an element with an
onclickjavascript event handler which calls a function that useswindow.locationto load another URL.
For case 2 I can imagine of:
- The loaded page contains an
iframetag that loads an URL inside the IFrame. This fires theNavigatingevent. - There is some JavaScript timer that is started on page load and when it fires, it uses
window.locationto load another URL. - The loaded page contains a meta refresh header tag to load another URL after some seconds.
So my question is:
How to detect inside the Navigating event (or any other mechanism) whether a redirect is triggered explicitly by the user or implicitly by the page?
Some more information
- The
WebBrowseris being used inside a windows based CMS backend application. - I therefore have full control over the content loaded inside the WebBrowser control.
- Meaning that I can manipulate the complete HTML string before being sent to the browser, if required.
- If it is more applicable, I also would love to get JavaScript-only solutions which I could inject into the HTML being loaded.
(Please note that I do believe this is not a duplicate of this SO posting)
回答1:
My take on this is capture user clicks on the web browser control. Have it set a flag that indicates that the user clicked on the web browser. If the flag is true, then allow redirection, if it isn't true don't allow it. Make sure to reset the flag after n number of seconds if no (or after) redirection is made.
回答2:
It seems you are trying to achieve anti-ads/popup/redirect pattern.
From web browser perspective.. clicking <a href="some.url"> is not different from javascript window.location = "some.url"; or 302 redirect response. there are no explicit signals, no such convenience methods.
The WebBrowser control is just a proxy to IE component. You can't intercept browser's engine or even disable/enable javascript as it's part of internet security option.
You have to create special logic to prevent every possible cases of redirection.
eg. verify HTML string then restrict some javascript pattern, header or iframe with Regex.Replace before render.
var scriptEx = new Regex("<script (.*?)</script>");
var iframeEx = new Regex("<iframe (.*?)</iframe>");
or intercept Navigating URL and cancel unsafe url, etc.
来源:https://stackoverflow.com/questions/14050548/how-to-distinguish-between-a-user-clicking-a-link-and-the-page-doing-an-automati