Nomadicus
07-30-2002, 09:10 PM
I've borrowed a function to get all the cookies contained in the document object from Paul McFredries "Using JavaScript." Here is his code :
function get_cookie(name_to_get) {
var cookie_pair
var cookie_name
var cookie_value
// Split all the cookies into an array
var cookie_array = document.cookie.split("; ")
// Run through the cookies
for (counter = 0; counter < cookie_array.length; counter++) {
// Split the cookie into a name/value pair
cookie_pair = cookie_array[counter].split("=")
cookie_name = cookie_pair[0]
cookie_value = cookie_pair[1]
// Compare the name with the name we want
if (cookie_name == name_to_get) {
// If this is the one, return the value
return unescape(cookie_value)
}
}
// If the cookie doesn't exist, return null
return null
}
This works just fine, as long as you keep everything inside the same page. But when I moved this function to a .js file, the function did not know what the document object was.
My question is, how can a rewrite this function (pass it an extra parameter) so the function has a reference to the document object, and can thus extract the cookies? I understand that cookies are actually "properties" of the document object.
I don't want to have to cut & paste this function to every web page that need it!
function get_cookie(name_to_get) {
var cookie_pair
var cookie_name
var cookie_value
// Split all the cookies into an array
var cookie_array = document.cookie.split("; ")
// Run through the cookies
for (counter = 0; counter < cookie_array.length; counter++) {
// Split the cookie into a name/value pair
cookie_pair = cookie_array[counter].split("=")
cookie_name = cookie_pair[0]
cookie_value = cookie_pair[1]
// Compare the name with the name we want
if (cookie_name == name_to_get) {
// If this is the one, return the value
return unescape(cookie_value)
}
}
// If the cookie doesn't exist, return null
return null
}
This works just fine, as long as you keep everything inside the same page. But when I moved this function to a .js file, the function did not know what the document object was.
My question is, how can a rewrite this function (pass it an extra parameter) so the function has a reference to the document object, and can thus extract the cookies? I understand that cookies are actually "properties" of the document object.
I don't want to have to cut & paste this function to every web page that need it!