简体   繁体   中英

onPopState() throwing error only in Google Chrome

I'm using AJAX to refresh content on pages and so trying to us the history API in HTML5. I have this working fine in all browsers apart from Google Chrome. The following code -

/**
 * Reloads the ajax content if the history.state is not null
 */
window.onpopstate = function(e){
    if(e.state !== null){
        initiate_load_updated_page(window.history.state.ajax_string, window.history.state.security, 0)
    }
}

Produces this error -

Uncaught TypeError: Cannot read property 'ajax_string' of undefined

Here is the code that I am using for pushState() -

/** Update the page history */
if(window.history.replaceState){ // Check for HTML5 support
    if(update_state !== 0){
        var object = {
            ajax_string: ajax_string,
            security: security,
        };
        window.history.pushState(object, title, permalink);
    }
}

I have read elsewhere that Google Chrome triggers an onPopState() event twice, but I'm not sure if this is the promblem here, and, if it is, how to solve it.

Thanks.

In your popstate handler you should be using e.state not window.history.state :

if(e.state !== null){
    initiate_load_updated_page(e.state.ajax_string, e.state.security, 0)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM