CookieModel.js 2.1 KB

12345678910111213141516
  1. export default class CookieModel extends SDK.SDKModel{constructor(target){super(target);}
  2. static cookieMatchesResourceURL(cookie,resourceURL){const url=resourceURL.asParsedURL();if(!url||!CookieModel.cookieDomainMatchesResourceDomain(cookie.domain(),url.host)){return false;}
  3. return(url.path.startsWith(cookie.path())&&(!cookie.port()||url.port===cookie.port())&&(!cookie.secure()||url.scheme==='https'));}
  4. static cookieDomainMatchesResourceDomain(cookieDomain,resourceDomain){if(cookieDomain.charAt(0)!=='.'){return resourceDomain===cookieDomain;}
  5. return!!resourceDomain.match(new RegExp('^([^\\.]+\\.)*'+cookieDomain.substring(1).escapeForRegExp()+'$','i'));}
  6. getCookies(urls){return this.target().networkAgent().getCookies(urls).then(cookies=>(cookies||[]).map(cookie=>SDK.Cookie.fromProtocolCookie(cookie)));}
  7. deleteCookie(cookie,callback){this._deleteAll([cookie],callback);}
  8. clear(domain,callback){this.getCookiesForDomain(domain||null).then(cookies=>this._deleteAll(cookies,callback));}
  9. saveCookie(cookie){let domain=cookie.domain();if(!domain.startsWith('.')){domain='';}
  10. let expires=undefined;if(cookie.expires()){expires=Math.floor(Date.parse(cookie.expires())/1000);}
  11. return this.target().networkAgent().setCookie(cookie.name(),cookie.value(),cookie.url(),domain,cookie.path(),cookie.secure(),cookie.httpOnly(),cookie.sameSite(),expires).then(success=>!!success);}
  12. getCookiesForDomain(domain){const resourceURLs=[];function populateResourceURLs(resource){const documentURL=resource.documentURL.asParsedURL();if(documentURL&&(!domain||documentURL.securityOrigin()===domain)){resourceURLs.push(resource.url);}}
  13. const resourceTreeModel=this.target().model(SDK.ResourceTreeModel);if(resourceTreeModel){resourceTreeModel.forAllResources(populateResourceURLs);}
  14. return this.getCookies(resourceURLs);}
  15. _deleteAll(cookies,callback){const networkAgent=this.target().networkAgent();Promise.all(cookies.map(cookie=>networkAgent.deleteCookies(cookie.name(),undefined,cookie.domain(),cookie.path()))).then(callback||function(){});}}
  16. self.SDK=self.SDK||{};SDK=SDK||{};SDK.CookieModel=CookieModel;SDK.SDKModel.register(SDK.CookieModel,SDK.Target.Capability.Network,false);