简体   繁体   English

Delphi 10.1和CEF3的Cookie出现问题

[英]Delphi 10.1 and CEF3 troubles with cookies

I have this code: 我有以下代码:

function VisitCookie(const name, value, domain, path: ustring;
  secure, httponly, hasExpires: Boolean; const creation, lastAccess,
  expires: TdateTime; Count, total: integer; out deleteCookie: Boolean)
  : Boolean;
begin
  RichEdit1.Lines.Add('cookie ' + inttostr(Count) + '/' + inttostr(total));
  RichEdit1.Lines.Add('name ' + name);
  RichEdit1.Lines.Add('value ' + value);
  RichEdit1.Lines.Add('domain ' + domain);
  RichEdit1.Lines.Add('path ' + path);
  RichEdit1.Lines.Add('secure ' + BoolToStr(secure));
  RichEdit1.Lines.Add('httponly ' + BoolToStr(httponly));
  RichEdit1.Lines.Add('hasExpires ' + BoolToStr(hasExpires));
  RichEdit1.Lines.Add('creation ' + DateToStr(creation));
  RichEdit1.Lines.Add('lastAccess ' + DateToStr(lastAccess));
  RichEdit1.Lines.Add('expires ' + DateToStr(expires));
  RichEdit1.Lines.Add('------------------------');
  Result := true;
end;

function GetCookies: Boolean;
begin
  CookieManager := TCefCookieManagerRef.Global(nil);
  CookieManager.VisitAllCookiesProc(VisitCookie);
end;

If I set Result := false in my function VisitCookie - I only get the value of the first cookie, that's all. 如果我在函数VisitCookie中将Result := false设置为-我仅获得第一个cookie的值,仅此而已。 Ie pass through the cookies does not happen. 即通过cookie不会发生。 But if I set Result := true - I got an access violation, but it works fine, until I have not so much cookies records in Chromium, for example 5-10 records. 但是,如果我将Result := true设置Result := true -我遇到了访问冲突,但工作正常,直到Chromium中没有那么多cookie记录,例如5-10条记录。 I have no idea why this happens. 我不知道为什么会这样。

The problem is that the visitor callback function of the VisitAllCookies method is executed in the context of a CEF worker thread, not in a context of the main thread hence you cannot access VCL controls from there. 问题在于, VisitAllCookies方法的访客回调函数是在CEF 工作线程的上下文中执行的,而不是在主线程的上下文中执行的,因此您不能从那里访问VCL控件。 The VisitAllCookies method returns immediately and the callback function is then called asynchronously from the CEF worker thread. VisitAllCookies方法立即返回,然后从CEF 工作线程异步调用回调函数。

There are many ways how to implement such cooperation. 如何进行这种合作有很多方法。 But it's not CEF specific. 但这不是CEF特有的。 It's about how to pass (or collect) certain data from a worker thread callback and pass it back to the main thread. 它是关于如何从工作线程回调中传递(或收集)某些数据并将其传递回主线程的。 Optionally also about taking the callback under control in a synchronous way (to interrupt running enumeration). 也可以选择同步方式控制回调(以中断正在运行的枚举)。

Here is one untested example (maybe too overcomplicated). 这是一个未经测试的示例(可能过于复杂)。 The principle remains, how to collect data from an uncontrolled thread callback function for the main thread (or take it under control in a synchronous way): 原理仍然是,如何从主线程的不受控制的线程回调函数中收集数据(或以同步方式在控制之下):

type
  TCookie = record
    Name: string;
    Value: string;
    Expires: TDateTime;
  end;

  TProcessCookieEvent = procedure(Sender: TObject; const Cookie: TCookie;
    const IsLast: Boolean; var Delete: Boolean; var Cancel: Boolean) of object;

  TCookieManager = class
  private
    FWndHandle: HWND;
    FOnProcessCookie: TProcessCookieEvent;
  protected
    procedure WndProc(var Msg: TMessage); virtual;
  public
    constructor Create;
    destructor Destroy; override;
    procedure ProcessCookies(Timeout: UINT = 5000);
    property OnProcessCookie: TProcessCookieEvent read FOnProcessCookie write FOnProcessCookie;
  end;

implementation

const
  PA_CANCEL = 1;
  PA_DELETE = 2;
  CM_PROCESSCOOKIE = WM_USER + 100;

type
  PCookie = ^TCookie;

constructor TCookieManager.Create;
begin
  inherited;
  FWndHandle := AllocateHWnd(WndProc);
end;

destructor TCookieManager.Destroy;
begin
  DeallocateHWnd(FWndHandle);
  inherited;
end;

procedure TCookieManager.WndProc(var Msg: TMessage);
var
  Delete: Boolean;
  Cancel: Boolean;
  IsLast: Boolean;
begin
  if Msg.Msg = CM_PROCESSCOOKIE then
  begin
    Msg.Result := 0;

    if Assigned(FOnProcessCookie) then
    try
      Delete := False;
      Cancel := False;
      IsLast := Boolean(Msg.wParam);

      FOnProcessCookie(Self, PCookie(Msg.lParam)^, IsLast, Delete, Cancel);

      if Delete then
        Msg.Result := Msg.Result or PA_DELETE;
      if Cancel then
        Msg.Result := Msg.Result or PA_CANCEL;
    except
      Application.HandleException(Self);
    end;
  end
  else
    Msg.Result := DefWindowProc(FWndHandle, Msg.Msg, Msg.wParam, Msg.lParam);
end;

procedure TCookieManager.ProcessCookies(Timeout: UINT = 5000);
var
  CookieManager: ICefCookieManager;
begin
  CookieManager := TCefCookieManagerRef.Global(nil);
  CookieManager.VisitAllCookiesProc(

    { this function will be called asynchronously from a CEF worker thread }
    function(const Name, Value, Domain, Path: UString; Secure, HTTPOnly,
      HasExpires: Boolean; const Creation, LastAccess, Expires: TDateTime;
      Count, Total: Integer; out DeleteCookie: Boolean): Boolean
    var
      MsgRet: DWORD;
      Cookie: TCookie;
      IsLast: Boolean;
    begin
      { initialize cancel of enumeration and no cookie deletion }
      Result := False;
      DeleteCookie := False;

      { fill the cookie structure }
      Cookie.Name := string(Name);
      Cookie.Value := string(Value);
      Cookie.Expires := Expires;

      { determine if it's the last enumerated cookie }
      IsLast := Count = Total-1;

      { yes, I'm doing what many would not do, but let me explain, this is not
        SendMessage, that could get stuck forever when the message pump of the
        receiver got stucked so I've let this thread responsive (SMTO_NORMAL),
        let this call fail when the receiver is "hung" (SMTO_ABORTIFHUNG) and
        let the function fail if the receiver is destroyed (SMTO_ERRORONEXIT)
        and there is the timeout, in which the receiver needs to process this
        message (if the message is not processed for some reason, enumerating
        stops) }
      if SendMessageTimeout(FWndHandle, CM_PROCESSCOOKIE, WPARAM(IsLast),
        LPARAM(@Cookie), SMTO_NORMAL or SMTO_ABORTIFHUNG or SMTO_ERRORONEXIT,
        Timeout, MsgRet) <> 0 then
      begin
        Result := MsgRet and PA_CANCEL <> PA_CANCEL;
        DeleteCookie := MsgRet and PA_DELETE = PA_DELETE;
      end;
      { else GetLastError and try to signal error by posting another message }
    end;

  );
end;

And a possible usage: 以及可能的用法:

type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
    procedure Button1Click(Sender: TObject);
  private
    FCookieList: TList<TCookie>;
    FCookieManager: TCookieManager;
    procedure DoProcessCookie(Sender: TObject; const Cookie: TCookie;
      const IsLast: Boolean; var Delete: Boolean; var Cancel: Boolean);
  end;

implementation

procedure TForm1.FormCreate(Sender: TObject);
begin
  FCookieList := TList<TCookie>.Create;
  FCookieManager := TCookieManager.Create;
  FCookieManager.OnProcessCookie := DoProcessCookie;
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
  FCookieManager.Free;
  FCookieList.Free;
end;

procedure TForm1.DoProcessCookie(Sender: TObject; const Cookie: TCookie;
  const IsLast: Boolean; var Delete: Boolean; var Cancel: Boolean);
begin
  { IsLast signals last enumerated cookie, Delete output parameter can delete
    the currently enumerated cookie, and Cancel output parameter can stop the
    enumeration }
  FCookieList.Add(Cookie);
  if IsLast then
    ShowMessage('All cookies has been enumerated!');
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  FCookieList.Clear;
  FCookieManager.ProcessCookies;
end;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM