Fra*_*yer 14 javascript google-chrome google-chrome-extension
我正在尝试使用此代码专门从域中获取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>
Run Code Online (Sandbox Code Playgroud)
问题是警报总是说未定义.但是,如果我改变了
ID = cookie.value;
Run Code Online (Sandbox Code Playgroud)
至
alert(cookie.value);
Run Code Online (Sandbox Code Playgroud)
它工作正常.如何保存以后使用的值?
更新:如果我在脚本运行后从chrome控制台调用alert(ID),它似乎有效.如何设置我的代码以等到chrome.cookies.get完成运行?
ser*_*erg 26
几乎所有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);
});
Run Code Online (Sandbox Code Playgroud)
任何依赖于 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>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
33420 次 |
最近记录: |