Magento中如何使用cookies
使用ManagerCookie管理cookies
<?php
namespace MagenestManagerCookieHelper;
use MagentoFrameworkSessionSessionManagerInterface;
class ExampleCookie {
protected $cookieManager;
protected $cookieMetadataFactory;
public function __construct(
MagentoFrameworkStdlibCookieManagerInterface $cookieManager,
MagentoFrameworkStdlibCookieCookieMetadataFactory $cookieMetadataFactory
)
{
$this->cookieManager = $cookieManager;
$this->cookieMetadataFactory = $cookieMetadataFactory;
}
/**
* get cookie by name
*/
public function getCookie($cookieName) {
return $this->cookieManager->getCookie($cookieName);
}
/**
* set public cookie
*/
public function setPublicCookie($cookieName, $value) {
$metadata = $this->cookieMetadataFactory
->createPublicCookieMetadata()
->setDuration(86400) // Cookie will expire after one day (86400 seconds)
->setSecure(true) //the cookie is only available under HTTPS
->setPath( /subfolder )// The cookie will be available to all pages and subdirectories within the /subfolder path
->setHttpOnly(false); // cookies can be accessed by JS
$this->_cookieManager->setPublicCookie(
$cookieName,
$value,
$metadata
);
}
/**
* set sensitive cookie
*/
public function setSensitiveCookie($cookieName, $value) {
$metadata = $this->cookieMetadataFactory
->createSensitiveCookieMetadata()
->setPath( )// for global
->setDomain( .example.com );// cookie will be available for www.example.com, example.com and will not be available for anotherexample.com
$this->_cookieManager->setSensitiveCookie(
$cookieName,
$value,
$metadata
);
}
}
在Magenton中有两种类型的cookie。它们是公共敏感cookie:
Public cookies: JS 可以访问
Sensitive cookies:JS不可访问
设置cookie时,需要设置原始cookie数据和一些元数据。此元数据包括cookie的有效路径、cookie过期时间的持续时间等
JS操作cookies
<script type="text/javascript">
require([
jquery ,
jquery/jquery.cookie
], function ($) {
$(document).ready(function () {
var simple_cookie = $.cookie( name_cookie ); // Get Cookie Value, note: You can only get a cookie if it is public
if(!simple_cookie) {
$.cookie( name_cookie , value of cookie , {expires: 86400}); // Set Cookie with metadata (note the cookies set here are public)
}else {
console.log(simple_cookie);
}
});
</script>
© 版权声明
文章版权归作者所有,未经允许请勿转载。如内容涉嫌侵权,请在本页底部进入<联系我们>进行举报投诉!
THE END



















暂无评论内容