首页 > 其他分享 >delphi 操作 TEdgeBrowser 获取与设置 Cookie

delphi 操作 TEdgeBrowser 获取与设置 Cookie

时间:2023-04-28 09:48:00浏览次数:55  
标签:begin end TEdgeBrowser delphi DispMsg Cookie AWebView2 procedure string

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

 

标签:begin,end,TEdgeBrowser,delphi,DispMsg,Cookie,AWebView2,procedure,string
From: https://www.cnblogs.com/lackey/p/17360961.html

相关文章

  • Delphi 抓图后打印这张图片,弹出打印属性框
    如果用窗体.print打印的话,会导致一些控件打印不出来,比如下拉列表,还有打印TChart也会导致只打印TChart的原始状态,而不会打印有数据的TChart所以我就想到了先抓图,后打印抓图后下拉列表和TChart都正常显示了,可是还有一点不好,就是下拉列表中的值是显示......
  • javascript操作cookie
    functionsetCookie(name,value){varDays=30;varexp=newDate();exp.setTime(exp.getTime()+Days*24*60*60*1000);document.cookie=name+"="+escape(value)+";expires="+exp.toGMTString();......
  • delphi 仿一下手机端淡入淡出的信息提示框
    先看效果:设计界面也很简单: 下面这个是个From,不是Frame.把它的边框设置为none,然后position设置在父级中央或者桌面中央,看个人喜欢吧.加个label,弯角搞一搞,其他也搞得好看一点.这里推荐SC组件.然后加个计时器.这里说一下定时器的interval属性,时间越长,越显得卡顿,上面......
  • 【谷歌插件开发】获取当前网站COOKIE并上报HTTP-API
    一背景由于本人每天需要登录网站查看数据并分析统计汇总,而每次机械式地搜索和简单计算,十分繁琐。我们可以写个定时任务,每天根据cookie获取网站数据并遍历统计。脚本得以成功执行的关键是需要获取到COOKIE故,写了个谷歌插件用来上报COOKIE二代码总目录三上代码manifest......
  • delphiXE10 代码结构高亮线风格单双设置
    勾上就是这个样式: 不勾就是这个样式: ......
  • JS逆向中 cookie加密的HOOK方法
    Object.defineProperty(obj,prop,descriptor)其中,参数obj是要定义属性的对象,    prop是要定义或修改的属性名,    descriptor是属性描述符对象。     属性描述符对象的属性包括value、writable、enumerable、configurable和get和se......
  • JS逆向实战13——某市公共资源交易中心Cookie混淆加密
    "本文地址:https://www.cnblogs.com/zichliang/p/17346860.html目标网站aHR0cDovL2xkZ2d6eS5obmxvdWRpLmdvdi5jbi9sZGp5engvanl4eC9saXN0LnNodG1s网站分析经过浏览器抓包,我们可知这个网站会先发出一个412请求,然后附带一个js然后返回正常的页面。经过我们代码测试可知如......
  • cookie、sessionStorage 和 localStorage
    cookie、sessionStorage和localStoragecookie1.基本概念Cookie是保存在计算机上的一种文件。当我们使用计算机浏览网页时,服务器会生成一个证书并将其返回给我们的计算机。这个证书就是cookie。一般来说,cookie是服务器写给客户端的文件,也可以称为浏览器缓存。简单来说,它可以......
  • Cookie禁用使用Session值方法
    Cookie禁用使用Session值方法:首先:    PHP中的Session在默认情况下是使用客户端的Cookie来保存SessionID的,所以当客户端的cookie出现问题的时候就会影响Session了。必须注意的是:Session不一定必须依赖Cookie,这也是Session相比Cookie的实用之处。当客户端的Cookie被禁用或出......
  • Cookie基本使用
    cookie是什么?是由服务器端生成,发送给User-Agent(一般指浏览器),浏览器将cookie以键值对的形式保存到某个目录下的文本文件内。下次请求该网站时就把cookie发送回服务器。(cookie就是一个小文件,浏览器对其大小一般限制在4k,用来记录一些信息(一般用作标识))为什么有cookie?web应用程......