Search code examples
delphibrowserkeybackspace

How to Disable Backspace in WebBrowser


When I press Backspace, Web-browser will go to previous page. How can I disable it without preventing the clearing text ability?


Solution

  • TWebBrowser doesn't seem to have an OnKeydown event, and it also has many other problems. I usually forget it and go to TEmbeddedWB (embedded web browser component pack), and it has better features.

    I wrote some code to try to detect if we are in an edit control, and only conditionally block backspace keys, since as Paktas says, simply blocking the OnKey event would break editing in
    web page forms, using TEmbeddedWB, the code looks like this:

    procedure TForm2.FormKeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    var
      element: IHTMLElement;
      elementTagName: String;
    begin
      // form contains field: EmbeddedWB1: TEmbeddedWB which is an improved version of TWebBrowser.
      element := EmbeddedWB1.GetActiveElement;
      if Assigned( element ) then
        begin
          elementTagName := element.tagName;
        end;
    
     if ( not SameText( elementTagName, 'INPUT' ) ) 
       and ( not SameText( elementTagName, 'TEXTAREA' ) ) then
      if    ((Key= VK_LEFT) and (Shift = [ssAlt]))
         or ((Key= VK_RIGHT) and (Shift = [ssAlt]))
         or (Key= VK_BROWSER_BACK)
         or (Key= VK_BROWSER_FORWARD)
         or(Key = VK_BACK) then
          begin
            Key := 0; { block backspace, but not in INPUT or TEXTAREA. }
            Exit;
          end;
    
    
    end;