在TMS Web Core网站中使用 Delphi 代码获取/设置浏览器Cookie

7uzetpgm  于 2023-10-18  发布在  其他
关注(0)|答案(2)|浏览(158)

在JavaScript中,使用Cookie非常简单。您可以通过document.cookie代码获取和设置cookie。
下面是我编写的获取和设置Cookie的示例JavaScript代码:

function getCookie(cookie_name) {
    const name = cookie_name + "=";
    const decodedCookie = decodeURIComponent(document.cookie);
    const ca = decodedCookie.split(';');
    for(let i = 0; i <ca.length; i++) {
        let c = ca[i];
        while (c.charAt(0) == ' ')
            c = c.substring(1);
        if (c.indexOf(name) == 0)
            return c.substring(name.length, c.length);
    }
    return "";
}

function setCookie(cookie_name, value, minutes) {
    let expires = "";
    if (minutes) {
        let date = new Date();
        date.setTime(date.getTime()+(minutes*60*1000));
        expires = "; expires="+date.toUTCString();
    }
    document.cookie = cookie_name + "=" + value + expires + ";SameSite=Strict; path=/";
}

如何在TMS Web Core中使用 Delphi 获取和设置Cookie?

jq6vz3qz

jq6vz3qz1#

您可以使用WEBLib.Cookies单元中的TCookies类获取和设置cookie。
下面是我用纯 Delphi 代码编写的获取和设置cookie的两个函数:

uses WEBLib.Cookies, System.DateUtils;

...

procedure SetCookie(cookie_name, value: String; minutes: UInt64);
var
  Cookies: TCookies;
begin
  Cookies := TCookies.Create;
  Try
    Cookies.Add(cookie_name,value, IncMinute(Now,minutes));
    Cookies.SetCookies;
  Finally
    Cookies.Free;
  End;
end;

function GetCookie(cookie_name: String): String;
var
  Cookies: TCookies;
  Cookie: TCookie;
begin
  Result := '';
  Cookies := TCookies.Create;
  Try
    Cookies.GetCookies;
    Cookie := Cookies.Find(cookie_name);
    if Assigned(Cookie) then
      Result := Cookie.Value;
  Finally
    Cookies.Free;
  End;
end;
bvn4nwqk

bvn4nwqk2#

我建议使用另一个答案,因为这是 Delphi 的方法,但是如果你想在不使用WEBLib.Cookies单元的情况下获取和设置cookie,那么你可以使用下面的两个函数:

procedure SetCookie(cookie_name, value: String; minutes: UInt64);
begin
  asm
    let expires = '';
    if (minutes) {
      let date = new Date();
      date.setTime(date.getTime()+(minutes*60*1000));
      expires = "; expires="+date.toUTCString();
    }
    document.cookie = cookie_name + "=" + value + expires + ";SameSite=Strict; path=/";
  end;
end;

function GetCookie(cookie_name: String): String;
begin
  Result := '';
  cookie_name := cookie_name + '=';
  asm
    const decodedCookie = decodeURIComponent(document.cookie);
    const ca = decodedCookie.split(';');
    for(let i = 0; i <ca.length; i++) {
      let c = ca[i];
      while (c.charAt(0) == ' ')
        c = c.substring(1);
      if (c.indexOf(name) == 0)
        Result = c.substring(name.length, c.length);
    }
    Result = "";
  end;
end;

上面的代码几乎与另一个答案相同,但它混合使用了 Delphi 和JavaScript代码。这个答案也不需要WEBLib.CookiesSystem.DateUtils单位。

相关问题