Как я могу остановить Chromium от создания окна хоста "WebViewHost" при запуске веб-браузера пользователя по умолчанию? - PullRequest
5 голосов
/ 12 февраля 2012

Я использую веб-браузер Chromium в своем приложении Delphi 6.

Всякий раз, когда пользователь нажимает на веб-ссылку на отображаемой в данный момент веб-странице, которой нет на моем основном веб-сайте, я запускаю его веб-браузер по умолчанию с URL-адресом, открывая URL-адрес с помощью функции Windows ShellExecute () с помощью ' Откройте глагол. Я делаю это из обработчика событий BeforeBrowse() и одновременно отменяю навигацию.

Другими словами, я не показываю внешние URL-адреса в элементе управления Chromium, а вместо этого показываю их в веб-браузере пользователя по умолчанию.

Работает нормально, но иногда я также получаю отдельное всплывающее окно, принадлежащее моему приложению, которое занимает около половины полностью пустого экрана (пустая белая область клиента с моей темой Windows). Имя класса Windows для окна - "webviewhost".

Может кто-нибудь сказать мне, как подавить это "призрачное" окно?

1 Ответ

9 голосов
/ 13 февраля 2012

Проблема здесь с всплывающими окнами.Они создаются до наступления события OnBeforeBrowse, и вы отменяете их навигацию, чтобы они выглядели как призраки.

Вы можете предотвратить их создание, установив результат OnBeforePopup событие для True, но это завершит навигацию, поэтому OnBeforeBrowse не будет запущено.Если вы последуете этим путем, то вам придется выполнить действие ShellExecute в событии OnBeforePopup.

procedure TForm1.Chromium1BeforePopup(Sender: TObject;
  const parentBrowser: ICefBrowser; var popupFeatures: TCefPopupFeatures;
  var windowInfo: TCefWindowInfo; var url: ustring; var client: ICefBase;
  out Result: Boolean);
begin
  // you can set the Result to True here and block the window creation at all,
  // but then you will stop also the navigation and the OnBeforeBrowse event
  // won't be fired, so if you will follow this way then you'll have to perform
  // your ShellExecute action here as well

  if url <> 'http://www.yourdomain.com' then
  begin
    Result := True;
    ShellExecute(Handle, 'open', PChar(url), '', '', SW_SHOWNORMAL);
  end;
end;

Другой способ заключается вустановите флаг m_bWindowRenderingDisabled в значение True в событии OnBeforePopup, что должно препятствовать созданию всплывающего окна (как описано в ceflib.pas, а нев официальной документации, IMHO, окно создано, но остается скрытым, и я надеюсь, что это не приведет к утечке, не проверили это), и навигация будет продолжена, так что событие OnBeforePopup будетполучить увольнение.

procedure TForm1.Chromium1BeforePopup(Sender: TObject;
  const parentBrowser: ICefBrowser; var popupFeatures: TCefPopupFeatures;
  var windowInfo: TCefWindowInfo; var url: ustring; var client: ICefBase;
  out Result: Boolean);
begin
  // you can set the m_bWindowRenderingDisabled flag to True here what should
  // prevent the popup window to be created and since we don't need to take
  // care about substitute parent for popup menus or dialog boxes of this popup
  // window (because we will cancel the navigation anyway) we don't need to set
  // the WndParent member here; but please check if there are no resource leaks
  // with this solution because it seems more that the window is just hidden

  if url <> 'http://www.yourdomain.com' then
    windowInfo.m_bWindowRenderingDisabled := True;
end;

Следующий код является симуляцией вашей проблемы (в this tutorial в качестве примера используется ссылка my popup в нижней части страницы, которая при нажатии откроет всплывающее окно).

uses
  ShellAPI, ceflib, cefvcl;

const
  PageURL = 'http://www.htmlcodetutorial.com/linking/linking_famsupp_72.html';
  PopupURL = 'http://www.htmlcodetutorial.com/linking/popupbasic.html';

procedure TForm1.FormCreate(Sender: TObject);
begin
  Chromium1.Load(PageURL);
end;

procedure TForm1.Chromium1BeforeBrowse(Sender: TObject;
  const browser: ICefBrowser; const frame: ICefFrame;
  const request: ICefRequest; navType: TCefHandlerNavtype; isRedirect: Boolean;
  out Result: Boolean);
begin
  if request.Url = PopupURL then
  begin
    Result := True;
    ShellExecute(Handle, 'open', PChar(request.Url), '', '', SW_SHOWNORMAL);
  end;
end;

procedure TForm1.Chromium1BeforePopup(Sender: TObject;
  const parentBrowser: ICefBrowser; var popupFeatures: TCefPopupFeatures;
  var windowInfo: TCefWindowInfo; var url: ustring; var client: ICefBase;
  out Result: Boolean);
begin
{
  // Solution 1
  // this will block the popup window creation and cancel the navigation to
  // the target, so we have to perform the ShellExecute action here as well
  if url = PopupURL then
  begin
    Result := True;
    ShellExecute(Handle, 'open', PChar(url), '', '', SW_SHOWNORMAL);
  end;
}
{
  // Solution 2
  // or we can set the m_bWindowRenderingDisabled flag to True and the window
  // won't be created (as described in ceflib.pas), but the navigation continue
  if url = PopupURL then
    windowInfo.m_bWindowRenderingDisabled := True;
}
end;
...