Javascript 在谷歌浏览器扩展程序中获取 cookie
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5892176/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting cookies in a google chrome extension
提问by Franz Payer
I am trying to get a cookie specifically from a domain using this code:
我正在尝试使用以下代码专门从域中获取 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>
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?
更新:看来,如果我在脚本运行后从 chrome 控制台调用 alert(ID) ,它就可以工作。如何将我的代码设置为等到 chrome.cookies.get 完成运行?
回答by serg
Almost all Chrome API calls are asynchronous, so you need to use callbacks to run code in order:
几乎所有的 Chrome API 调用都是异步的,因此您需要使用回调来按顺序运行代码:
function getCookies(domain, name, callback) {
chrome.cookies.get({"url": domain, "name": name}, function(cookie) {
if(callback) {
callback(cookie.value);
}
});
}
//usage:
getCookies("http://www.example.com", "id", function(id) {
alert(id);
});
回答by David Mills
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:
任何依赖于 chrome.cookies.get() 调用结果的代码都必须从回调中调用。在您的示例中,只需等待回调触发,然后再显示警报:
<script language="JavaScript" type="text/javascript">
var ID;
function getCookies(domain, name)
{
chrome.cookies.get({"url": domain, "name": name}, function(cookie) {
ID = cookie.value;
showId();
});
}
function showId() {
alert(ID);
}
getCookies("http://www.example.com", "id")
</script>