到目前为止,我一直在尝试初始化根登录页面useEffect中的cc对象:
const CC = require( "CookieConsent")
....
useEffect(() => {
const cc = new CC({
container: document.getElementById("cookieconsent"),
palette: {
popup: { background: "#1aa3ff" },
button: { background: "#e0e0e0" },
},
revokable: true,
onStatusChange: function(status) {
console.log(this.hasConsented() ?
'enable cookies' : 'disable cookies');
},
"position": "bottom-left",
"theme": "classic",
"domain": "<myAppURL>",
"secure": true,
"content": {
"header": 'Cookies used on the website!',
"message": 'This website uses cookies to improve your experience.',
"dismiss": 'Got it!',
"allow": 'Allow cookies',
"deny": 'Decline',
"link": 'Learn more',
"href": 'https://www.cookiesandyou.com',
"close": '❌',
"policy": 'Cookie Policy',
"target": '_blank',
}
})
}, [])
return (
...
<div id="cookieconsent"></div>
...
)
....当我这样做的时候,我得到了"ReferenceError: window is not defined“错误。有什么想法我可以实现它吗?
Osano git:https://github.com/osano/cookieconsent/
发布于 2021-07-15 22:45:52
您应该动态导入"CookieConsent“,以便它只在客户端加载,而不是在服务器上加载。例如:
// remove
const CC = require( "CookieConsent")
// add
const CC = dynamic(() => import("../node_modules/cookieconsent/src/cookieconsent"), {
ssr: false
});您必须确保从原始的require语句显式编写到"CookieConsent“的路径,就像我的动态导入示例一样。
然后,窗口对象将可用,因为窗口对象在浏览器中仅在客户端可用,作为窗口。
看看这里的文档以供参考:https://nextjs.org/docs/advanced-features/dynamic-import
https://stackoverflow.com/questions/67484131
复制相似问题