user1010701
user1010701

Reputation: 59

Remember my jquery cookie values in new window

Not sure how to do this, I'm setting a jQuery cookie on a link on a page which then opens a new window. So on window 1 - cookie value is set to XXX. Window 2 is a page where user can update this cookie value to anything i.e. XYX, YYY etc.

So I want to be able to update the cookie value in window 1 with what the user has changed in window 2.

At the moment I have 2 windows one with $.mycookie(test, xxx) and $.mycookie(test, yyy). If user closes window 2 his change is not updated in window 1.

Upvotes: 2

Views: 999

Answers (2)

Anthony Hatzopoulos
Anthony Hatzopoulos

Reputation: 10537

You are correct, you need to refresh the opener window.

Window-1 via javascript opens Window-2 (the popup) and this popup needs to have a function called when unload event is fired for when it closes and/or when a button/link is clicked that refreshes the parent window. Cookie changes that happen in the way you are doing them can only be active after a refresh.

Simple Window-2 Example:

<script>
function whatever() {
    $.cookie("test", $('input[name=cookievalue]').val());
    if (window.opener != null) {
        window.opener.location.reload();
        window.close();
    }
}

$('button[name=clicker"]').bind('click', function(){
    whatever();
});

/* optionall you can also do an unload event, 
 * but you should probably check if you ran whatever() more then 
 * once and not run it a second time.
 */
$(window).unload(function(){ 
    whatever();
});
</script>

<input type="text" value="" name="cookievalue">
<button name="clicker">Change Cookie and close</button>

Upvotes: 0

George D
George D

Reputation: 2365

To explicitly make the cookie available for all paths on your domain, make sure the path is set:

$.cookie("example", "foo", { path: '/' });

To limit it to a specific path instead:

$.cookie("example", "foo", { path: '/foo' });

If set to '/', the cookie will be available within the entire domain . If set to '/foo/', the cookie will only be available within the /foo/ directory and all sub-directories such as /foo/bar/ of domain . The default value is the current directory that the cookie is being set in.

Upvotes: 1

Related Questions