How to detect navigation in TWebBrowser as opposed to clicking URLs?
delphi, twebbrowser
Solution
Please note that the following is undocumented. Some `people say` and it works for me (on Windows 7 64-bit, with Internet Explorer 10) to check for a magical constant of the `Flags` parameter. If the `Flags` parameter of the `OnBeforeNavigate2` event equals to 64, it was the user, who navigated through the link. If the `Flags` parameter equals to 0, it was the `IWebBrowser2::Navigate` method, who invoked the navigation. In code it would be:
procedure TForm1.WebBrowser1BeforeNavigate2(ASender: TObject;
const pDisp: IDispatch; const URL, Flags, TargetFrameName, PostData,
Headers: OleVariant; var Cancel: WordBool);
begin
if (Flags and navHyperlink) = navHyperlink then
ShowMessage('User clicked a link...')
else
ShowMessage('IWebBrowser2::Navigate has been invoked...');
end;
I wouldn't be much surprised, if that is just unintentionally undocumented flag value because that part of the MSDN is horrible.
Problem
I'm using a `TWebBrowser` to display some HTML content (locally). The application is split in half, the top half has 5 tabs and the bottom half is the web browser. The contents of the browser change often, for example when changing to a different tab. The content which is shown includes URLs which I need to prevent and stop every click. I'm trying to use the event `OnBeforeNavigate2` which does detect every link clicked, but also detects when I programatically call `Navigate`. So, it winds up never navigating anywhere. I tried wrapping the `Navigate` call so I always call something like... ``` procedure TForm1.Nav(const S: String); begin FLoading:= True; try Web.Navigate(S); Sleep(50); finally FLoading:= False; end; end; ``` (Sleep was just to try and give it a split second to wait) And then capturing the call... ``` procedure TForm1.WebBeforeNavigate2(ASender: TObject; const pDisp: IDispatch; const URL, Flags, TargetFrameName, PostData, Headers: OleVariant; var Cancel: WordBool); begin if not FLoading then Cancel:= True; end; ``` No luck trying this trick. How can I detect when the page or user navigates but not when the browser is instructed to navigate?