关于通用Cookie脚本概念及Tag Manager Cookie代码的技术问询
Hey there! Let's walk through your two questions about the cookie code you're building for Tag Manager—these are really solid questions to clarify when working with browser cookies.
That line of code document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/"; does exactly what you're thinking, with a few key details:
- No matter if you pass a number, string, or other basic data type as
cvalue, JavaScript will automatically convert it to a string before storing it indocument.cookie. Browsers only store cookies as plain text, so there's no way to save raw numeric values directly—you'd have to convert them back to numbers when retrieving if needed. - This cookie will persist in the user's browser until one of three things happens:
- The expiration time specified in the
expiresparameter is reached - The user manually clears their browser's cookies
- Another piece of code modifies or deletes the cookie via
document.cookie
- The expiration time specified in the
- The
path=/part ensures the cookie is accessible across every page of your website, not just the page where it was created.
First, let's set the context: most getCookie functions split the document.cookie string (which is a semicolon-separated list of name=value pairs) into an array, then loop through each entry to find the one we need.
That if check serves a specific purpose:
- It verifies that the current cookie entry starts exactly with the name we're searching for. For example, if you're looking for a cookie named
"sessionId", this will match"sessionId=abc123"but won't accidentally match"userSessionId=xyz789"(since that entry starts with"userSessionId", soindexOf("sessionId")would return 4, not 0). - A small caveat: this isn't 100% foolproof. If you have a cookie named
"user"and another named"userId", searching for"user"would incorrectly match"userId"because"userId"starts with"user". A more robust approach would be to checkc.startsWith(name + '=')—this ensures we're matching the full cookie name, since every cookie entry follows thename=valueformat. - Once the match is confirmed,
c.substr(name.length + 1)grabs the value part by skipping past thename=prefix (hence the+1to account for the equals sign).
内容的提问来源于stack exchange,提问作者Pak Hang Leung
相关产品推荐
相关产品推荐

