在Google Chrome浏览器扩展程序中获取Cookie [英] Getting cookies in a google chrome extension
本文介绍了在Google Chrome浏览器扩展程序中获取Cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
< script language =javascript我试图从一个域中获得一个cookie,类型= 文本/ JavaScript的 >
var ID;
$ b $ 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;
至
警报(cookie.value);
它正常工作。更新:如果我在脚本运行后从chrome控制台调用警报(ID),它就会起作用。如何在稍后使用该值来保存该值? 如何设置我的代码等待,直到chrome.cookies.get完成运行?
解决方案
几乎所有的Chrome API调用都是异步的,所以你需要使用回调按顺序运行代码:
function getCookies(domain,name,callback){
(){
callback(cookie.value);
} {
});
}
//用法:
getCookies(http://www.example.com,id,函数(id){
alert( id);
});
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?
解决方案
Almost all Chrome API calls are asynchronous, so you need to use callbacks to run code in order:
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);
});
这篇关于在Google Chrome浏览器扩展程序中获取Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文