delphi 操作 TEdgeBrowser 获取与设置 Cookie

delphi 11.2 完整源码下载

详情请查看源码,现提供部分代码供大家查看

DELPHI智慧战神-技术群  603146133  原来的群已被查封,请大家加新群

unit uYouYouMgt;

interface

uses
  uSimpleBase, uEdgeCls, uIdhttpEx, System.SysUtils, System.StrUtils, uWebView2Horse, WebView2_TLb, uWebView2common,
  Winapi.ActiveX, Comobj, System.Variants;

type

  TYouYouMgt = class(TSimpleBase)
  private
    FCmd: integer;
    FIdhttp: TIdhttpEx;
    FSessionId: string;
    FWebView2Horse: TWebview2Horse;

    procedure OnExecScriptProcTing(AResult: HRESULT; AResultObjectAsJson: string);
    procedure OnCreateDoc();

    procedure OnWebResourceResponseReceivedTing(Sender: ICoreWebView2; Args: ICoreWebView2WebResourceResponseReceivedEventArgs);

    procedure OnGetCookiesTing(Sender: TWebview2Horse);

  public
    procedure Init;
    procedure GetVeriyCode;
    procedure Login;
  public
    constructor Create;
    destructor Destroy; override;
  public
    BoEdgeBrowser: uEdgeCls.TEdgeBrowser;
    MoblieNum: string;
    MainUrl: string;
    CodeStr: string;
  end;

implementation

{ TYouYouMgt }
uses
  uOperateIndy, SuperObject, uStrUtils;

procedure TYouYouMgt.OnCreateDoc;
begin

  // FWebView2Horse.UpdateCookies(BoEdgeBrowser.DefaultInterface); 此句为设置到网页中去

  // 增加 拦截网址打开后的功能,让 OnWebResourceResponseReceivedTing 生效
  FWebView2Horse.AddFilter(BoEdgeBrowser.DefaultInterface, '*');

end;

procedure TYouYouMgt.OnExecScriptProcTing(AResult: HRESULT; AResultObjectAsJson: string);
begin
end;

procedure TYouYouMgt.OnGetCookiesTing(Sender: TWebview2Horse);
begin

  // 此处已获取到 cookie , 在  FWebView2Horse.CookieList 中
  DoOnMsg(FWebView2Horse.CookieList.ToDetail); // 显示cookie

end;

procedure TYouYouMgt.OnWebResourceResponseReceivedTing(Sender: ICoreWebView2; Args: ICoreWebView2WebResourceResponseReceivedEventArgs);
var
  LResponse: ICoreWebView2WebResourceResponseView;
  // LResponseHeaders: ICoreWebView2HttpResponseHeaders;
  LRequest: ICoreWebView2WebResourceRequest;
  // LRequestHeaders: ICoreWebView2HttpRequestHeaders;
  // LIt: ICoreWebView2HttpHeadersCollectionIterator;
  pUri: PWideChar;
  // pMethod: PWideChar;
  // pName, pValue: PWideChar;
  // LHasNext: integer;
  // pContentEncoding: PWideChar;
  // sContentEncoding: string;
  sTmpUrl: string;
  sUri: string;
  sPayLoad: string;
  J, E: ISuperObject;

begin
  Args.Get_Request(LRequest);
  LRequest.Get_uri(pUri);
  sUri := string(pUri);
  // DispMsg(pUri);
  Args.Get_Response(LResponse);

   DispMsg(string(pUri)); // 显示拦截到的 url;

  sTmpUrl := 'http://xxx/' ;// 弄一个合适的网址,只要打开此网址后有 cookie 就行了.

  if PosEx(sTmpUrl, sUri) > 0 then
  begin

    DispMsg('检测到已登录URL请求:' + sTmpUrl);

    FWebView2Horse.GetCookies(BoEdgeBrowser.DefaultInterface); // 获取 cookie;

  end;

end;

constructor TYouYouMgt.Create;
begin
  inherited;
  FIdhttp := TIdhttpEx.Create(nil);
  FWebView2Horse := TWebview2Horse.Create;

  // 当打开 url 后
  FWebView2Horse.OnWebResourceResponseReceived := self.OnWebResourceResponseReceivedTing;
  FWebView2Horse.OnGetCookies := self.OnGetCookiesTing;

end;

destructor TYouYouMgt.Destroy;
begin
  FIdhttp.Free;
  FWebView2Horse.Free;
  inherited;
end;

procedure TYouYouMgt.GetVeriyCode;
var
  sUrl: string;
  sHtml: string;
  sPayLoad: string;
  J: ISuperObject;
  sUid: string;
  G: TGUID;
begin

  sUrl := 'https://api.youpin898.com/api/user/Auth/SendSignInSmsCode';

  FIdhttp.Request.UserAgent := 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36';
  FIdhttp.Request.Accept := 'application/json, text/plain, */*';
  FIdhttp.Request.AcceptEncoding := 'gzip, deflate, br';
  FIdhttp.Request.AcceptLanguage := 'zh-CN,zh;q=0.9,de;q=0.8';
  FIdhttp.Request.ContentType := 'application/json';

  J := so();

  CreateGUID(G);

  sUid := LowerCase(G.ToString);

  sUid := ReplaceAll(sUid, '{', '');
  sUid := ReplaceAll(sUid, '}', '');

  DispMsg(sUid);

  FSessionId := sUid;

  J.S['Mobile'] := MoblieNum;
  J.S['SessionId'] := FSessionId;

  sPayLoad := J.AsString;
  DispMsg(sPayLoad);

  if IdhttpPost(FIdhttp, sPayLoad, sUrl, sHtml) then
  begin
    // DispMsg(FIdhttp.CookieMgr.CurCookies);
  end;

  DispMsg(sHtml);

end;

procedure TYouYouMgt.Init;
begin
  if Assigned(BoEdgeBrowser) then
  begin
    BoEdgeBrowser.OnEdgeMsg := self.OnDispMsgTing;
    BoEdgeBrowser.AppendCreateViewCompletedWorkProc(OnCreateDoc);
  end;
end;

procedure TYouYouMgt.Login;
var
  sUrl: string;
  sHtml: string;
  sPayLoad: string;
  J, jData: ISuperObject;
  w: TWkCookie;
begin

  sUrl := 'https://api.youpin898.com/api/user/Auth/SmsSignIn';

  FIdhttp.Request.UserAgent := 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36';
  FIdhttp.Request.Accept := 'application/json, text/plain, */*';
  FIdhttp.Request.AcceptEncoding := 'gzip, deflate, br';
  FIdhttp.Request.AcceptLanguage := 'zh-CN,zh;q=0.9,de;q=0.8';
  FIdhttp.Request.ContentType := 'application/json';

  J := so();

  J.S['Mobile'] := MoblieNum;
  J.S['SessionId'] := FSessionId;
  J.S['Code'] := CodeStr;

  sPayLoad := J.AsString;
  DispMsg(sPayLoad);

  if IdhttpPost(FIdhttp, sPayLoad, sUrl, sHtml) then
  begin
    // DispMsg(FIdhttp.CookieMgr.CurCookies);
  end;

  DispMsg(sHtml);

  { sHtml := LoadTextFromFile('登录成功.txt');
    J := so(sHtml);
    DispMsg(J.AsString); }

  J := so(sHtml);

  jData := J.O['Data'];

  FWebView2Horse.CookieList.ClearAndFreeAllItems;

  w := FWebView2Horse.CookieList.AddNewOne;

  w.CookieName := 'token';
  w.Value := jData.S['Token'];
  w.Domain := '.youpin898.com';

  DispMsg(w.ToStr);

  BoEdgeBrowser.Navigate(MainUrl);

end;

end.
View Code
unit uWebView2Horse;

interface

uses

  System.SysUtils, uSimpleBase, Windows, System.Classes, Winapi.ActiveX, Comobj, WebView2_TLb, uWebView2Common,
  System.Variants;

type

  TWebview2Horse = class;

  TOnWebResourceResponseReceived = procedure(Sender: ICoreWebView2; Args: ICoreWebView2WebResourceResponseReceivedEventArgs) of object;
  TOnNewWindowRequest = procedure(ANewWebView2: ICoreWebView2; Args: ICoreWebView2NewWindowRequestedEventArgs) of object;

  TOnGetCookies = procedure(Sender: TWebview2Horse) of object;

  TWebview2Horse = class(TSimpleBase)
  private
    FWebResourceResponseReceivedToken: EventRegistrationToken;
    FNewWindowToken: EventRegistrationToken;
  public

    constructor Create;
    destructor Destroy; override;

    procedure UpdateCookies(AWebView2: IInterface); // 将 cookies 写入浏览器
    procedure GetCookies(AWebView2: IInterface); // 获取 cookies 写入 CookieList;
    procedure TestHost(AWebView2: IInterface);
    procedure AddFilter(AWebView2: IInterface; AFilter: string);
    procedure AddNewWindowRequested(AWebView2: IInterface);

    function GetPayLoad(ARequest: ICoreWebView2WebResourceRequest): string;

  public
    CookieList: TWkCookieList;
    OnWebResourceResponseReceived: TOnWebResourceResponseReceived;
    OnNewWindowRequest: TOnNewWindowRequest;
    OnGetCookies: TOnGetCookies;
  end;

  TCoreWebView2WebResourceResponseViewGetContentCompletedHandler = class;

  TOnGetContent = procedure(Sender: TObject; ContentStream: TMemoryStream) of object;

  TCoreWebView2WebResourceResponseViewGetContentCompletedHandler = class(TInterfacedObject, ICoreWebView2WebResourceResponseViewGetContentCompletedHandler)
  public
    constructor Create;
    destructor Destroy; override;
    function Invoke(errorCode: HResult; const Content: IStream): HResult; stdcall;
  public
    ContentStream: TMemoryStream;
    OnGetContent: TOnGetContent;
  end;

implementation

uses
  uStrUtils;

procedure TWebview2Horse.AddFilter(AWebView2: IInterface; AFilter: string);
var
  LWebView2_2: ICoreWebView2_2;
begin

  // DispMsg('增加 web recevied');

  if Assigned(AWebView2) then
  begin

    LWebView2_2 := AWebView2 as ICoreWebView2_2;

    LWebView2_2.AddWebResourceRequestedFilter(pchar(AFilter), 0);
    LWebView2_2.add_WebResourceResponseReceived(CallBack<ICoreWebView2, ICoreWebView2WebResourceResponseReceivedEventArgs>.

      CreateAs<ICoreWebView2WebResourceResponseReceivedEventHandler>(

      function(const Sender: ICoreWebView2; const Args: ICoreWebView2WebResourceResponseReceivedEventArgs): HResult stdcall
      begin
        result := S_OK;
        if Assigned(OnWebResourceResponseReceived) then
          OnWebResourceResponseReceived(Sender, Args);
      end

      ), FWebResourceResponseReceivedToken);

  end
  else
  begin
    DoOnMsg('AWebView2 为 nil');
  end;

end;

procedure TWebview2Horse.AddNewWindowRequested(AWebView2: IInterface);
var
  LWebView2_2: ICoreWebView2_2;
begin

  // DispMsg('增加 NewWindowEvent');

  if Assigned(AWebView2) then
  begin

    LWebView2_2 := AWebView2 as ICoreWebView2_2;
    LWebView2_2.add_NewWindowRequested(CallBack<ICoreWebView2, ICoreWebView2NewWindowRequestedEventArgs>.CreateAs<ICoreWebView2NewWindowRequestedEventHandler>(

      function(const Sender: ICoreWebView2; const Args: ICoreWebView2NewWindowRequestedEventArgs): HResult stdcall
      { var
        LWV2: ICoreWebView2;
        pUrl: pchar;
        r: HResult;

        LWindowFeature: ICoreWebView2WindowFeatures; }
      begin

        result := S_OK;

        { r := Args.Get_NewWindow(LWV2);

          DispMsg(InttoStr(r));

          r := Args.Get_uri(pUrl);
          DispMsg(InttoStr(r));

          Sender.Get_Source(pUrl);

          DispMsg('pUrl:'+string(purl)); }

        // args.Set_NewWindow();
        // args.Get_WindowFeatures(LWindowFeature);
        // args.
        // args.Get_NewWindow(LWV2);
        // sender.Navigate(purl);
        // sender.
        // args.Get_Handled()

        // Args.Set_Handled(1);
        // Args.Set_NewWindow(Sender);

        if Assigned(OnNewWindowRequest) then
          OnNewWindowRequest(Sender, Args);

      end

      ), FNewWindowToken);

  end;

end;

constructor TWebview2Horse.Create;
begin
  inherited;
  CookieList := TWkCookieList.Create;
end;

destructor TWebview2Horse.Destroy;
begin
  CookieList.Free;
  inherited;
end;

procedure TWebview2Horse.GetCookies(AWebView2: IInterface);

var

  LWebView2_2: ICoreWebView2_2;
  LCookieMgt: ICoreWebView2CookieManager;

begin

  CookieList.ClearAndFreeAllItems;

  LWebView2_2 := AWebView2 as ICoreWebView2_2;
  LWebView2_2.Get_CookieManager(LCookieMgt);

  if Assigned(LCookieMgt) then
  begin

    LCookieMgt.GetCookies(nil, CallBack<HResult, ICoreWebView2CookieList>.CreateAs<ICoreWebView2GetCookiesCompletedHandler>(

      function(AResult: HResult; const CookieList: ICoreWebView2CookieList): HResult stdcall
      var
        i: integer;
        nCookieCount: Cardinal;
        LCookie: ICoreWebView2Cookie;
        pName, pValue, pDoMain, pPath: PWidechar;
        LWkCookie: TWkCookie;

      begin
        result := S_OK;
        CookieList.Get_Count(nCookieCount);

        for i := 0 to nCookieCount - 1 do
        begin
          CookieList.GetValueAtIndex(i, LCookie);

          if Assigned(LCookie) then
          begin

            LCookie.Get_name(pName);
            LCookie.Get_value(pValue);
            LCookie.Get_Domain(pDoMain);
            LCookie.Get_Path(pPath);

            LWkCookie := self.CookieList.AddNewOne;
            LWkCookie.CookieName := pName;
            LWkCookie.Value := pValue;
            LWkCookie.Path := pPath;
            LWkCookie.Domain := pDoMain;

          end;

        end;

        // DispMsg(self.CookieList.ToDetail);
        if Assigned(OnGetCookies) then
          OnGetCookies(self);

      end

      ));

  end
  else
    DoOnMsg('获取 ICoreWebView2CookieManager 失败');

end;

function TWebview2Horse.GetPayLoad(ARequest: ICoreWebView2WebResourceRequest): string;
var
  k: IStream;
  M: TMemoryStream;
begin
  result := '';
  k := nil;
  ARequest.Get_Content(k);
  if Assigned(k) then
  begin
    // result:
    M := TMemoryStream.Create;
    try
      IStreamToStream(k, M);
      result := StreamToStringInUtf8(M);
    finally
      M.Free;
    end;
  end;

end;

procedure TWebview2Horse.TestHost(AWebView2: IInterface);

var
  LWebView2: ICoreWebView2;
  // LSettings: ICoreWebView2Settings;
begin

  LWebView2 := AWebView2 as ICoreWebView2;

  if Assigned(LWebView2) then
  begin
  end;

end;

procedure TWebview2Horse.UpdateCookies(AWebView2: IInterface);

var

  LWebView2_2: ICoreWebView2_2;
  LCookieMgt: ICoreWebView2CookieManager;

  LCookie: ICoreWebView2Cookie;
  LWkCookie: TWkCookie;

begin

  LWebView2_2 := AWebView2 as ICoreWebView2_2;

  LWebView2_2.Get_CookieManager(LCookieMgt);

  if Assigned(LCookieMgt) then
  begin

    for LWkCookie in CookieList do
    begin
      LCookieMgt.CreateCookie(PWidechar(LWkCookie.CookieName), PWidechar(LWkCookie.Value), PWidechar(LWkCookie.Domain), PWidechar(LWkCookie.Path), LCookie);

      if Assigned(LCookie) then
        LCookieMgt.AddOrUpdateCookie(LCookie)
      else
        DoOnMsg('生成 ICoreWebView2Cookie 失败');

    end;

    CookieList.ClearAndFreeAllItems;

  end
  else
    DoOnMsg('获取 ICoreWebView2CookieManager 失败');

end;

{ TCoreWebView2WebResourceResponseViewGetContentCompletedHandler }

constructor TCoreWebView2WebResourceResponseViewGetContentCompletedHandler.Create;
begin
  inherited;
  ContentStream := TMemoryStream.Create;
end;

destructor TCoreWebView2WebResourceResponseViewGetContentCompletedHandler.Destroy;
begin
  ContentStream.Free;
  inherited;
end;

function TCoreWebView2WebResourceResponseViewGetContentCompletedHandler.Invoke(errorCode: HResult; const Content: IStream): HResult;
var
  LStatStg: TStatStg;
begin
  result := S_OK;

  ContentStream.Clear;

  if Content <> nil then
  begin
    Content.Stat(LStatStg, 09);
    IStreamToStream(Content, ContentStream, LStatStg.cbSize);
    ContentStream.Position := 0;
  end;

  if Assigned(OnGetContent) then
    OnGetContent(self, ContentStream);

end;

end.
View Code

 

posted on 2023-04-28 09:27  晓不得2013  阅读(512)  评论(0编辑  收藏  举报

导航