在 google chrome 扩展程序中获取 cookie
我正在尝试使用以下代码专门从域获取 cookie:
<script language="javascript" type="text/javascript">
var ID;
function getCookies(domain, name) {
chrome.cookies.get({"url": domain, "name": name}, function(cookie) {
ID = cookie.value;
});
}
getCookies("http://www.example.com", "id")
alert(ID);
</script>
问题是警报总是显示未定义。但是,如果我更改
ID = cookie.value;
为
alert(cookie.value);
它就可以正常工作。如何保存该值以供以后使用?
更新:看来,如果我在脚本运行后从 chrome 控制台调用警报(ID),它就会起作用。如何将代码设置为等待 chrome.cookies.get 完成运行?
I am trying to get a cookie specifically from a domain using this code:
<script language="javascript" type="text/javascript">
var ID;
function getCookies(domain, name) {
chrome.cookies.get({"url": domain, "name": name}, function(cookie) {
ID = cookie.value;
});
}
getCookies("http://www.example.com", "id")
alert(ID);
</script>
The problem is that the alert always says undefined. However, if I change
ID = cookie.value;
to
alert(cookie.value);
it works properly. How do I save the value to use later?
Update: It appears that if I call alert(ID) from the chrome console after the script runs, it works. How can I set my code to wait until chrome.cookies.get finishes running?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
几乎所有 Chrome API 调用都是异步的,因此您需要使用回调来按顺序运行代码:
Almost all Chrome API calls are asynchronous, so you need to use callbacks to run code in order:
任何依赖于 chrome.cookies.get() 调用结果的代码都必须从回调中调用。在您的示例中,只需等待回调触发,然后再显示警报:
Any code that depends on the result of the call to chrome.cookies.get() will have to be invoked from within the callback. In your example, just wait for the callback to fire before you show the alert:
获取域下的所有 cookie:
此脚本可以从弹出窗口和后台服务工作线程运行,但不能从内容脚本运行。
To get all cookies under a domain:
This script can be run from popup and background service worker but not a content script.