2016-05-14 75 views
1

我正在練習document.cookie屬性,並且能夠在我的FireFox瀏覽器中設置並返回Cookie。但是,當我試圖在谷歌瀏覽器中返回一些cookie時,我沒有返回任何內容。這是有原因的嗎?這裏是我的代碼jsfiddle爲什麼我無法在Google Chrome中返回Cookie?

HTML

<div id="ex1"> 
    <h2>Example 1</h2> 
    <p></p> 
    <h4>results:</h4> 
    <button id="btn">Return Cookie</button> 
    <button id="btn2">Set Cookie</button> 
</div> 

的Javascript

如果你在本地主機上設置cookie
function cText(text) { 
    return document.createTextNode(text); 
} 

function cElem(elem) { 
    return document.createElement(elem); 
} 

function attach(id, text, elem) { 
    var a = cText(text); 
    var b = cElem(elem); 
    b.appendChild(a); 

    var c = document.getElementById(id).appendChild(b); 
    return c; 
} 

document.getElementById('btn').onclick = function() { 
    var a = document.cookie; 
    attach('ex1', a, 'p'); 
} 

/* In order to make key = values you have to make a separate line for 
each name and value that you are going to put into the document.cookie*/ 
document.getElementById('btn2').onclick = function() { 
    document.cookie = "name = Michael Hendricks; expires =" + dayt + ";"; 
    document.cookie = "occupation = Shitty Retail Clerk; expires =" + dayt + ";"; 
    document.cookie = "age = 26 years old with big ol man boobs; expires =" + dayt + ";"; 

    console.log('cookie has been saved'); 
} 
+0

您的jsfiddle在我的50.0.2661.102中正常工作Chrome –

+0

@Gosha_Fighten是的,我看到它在jfiddle中有效。但是,當我將它添加到普通的html文件中並將其輸出爲chrome時,我不會返回任何值。 –

回答

0

域名必須爲空。

+0

你如何使一個域爲空? –

0

Chrome將不會爲'file://'協議(以及safari)設置cookie。 您可以使用'Web Server for Chrome'來測試您的本地網絡應用程序。

相關問題