Question

I've been trying to set a third party cookie using the following method:

SiteA

<img src="http://www.siteB.co.uk/cookie.php" />

SiteB

<script>

    document.cookie = "name=thirdpartytest; expires=07/07/2013; path=/;domain=SiteB.co.uk";

</script>

When I visit SiteB/cookie.php directly the cookie drops as expected. But accessing SiteA does not drop any cookie.

When I use the same methodology but use PHP to drop the cookie, it works great. Is there a reason why Javascript won't drop the cookie in this scenario? I thought it might be because there are no HTTP content-type headers being sent to say the .php page is an image. But I didn't seem to need that in place for the PHP version of the code to work.

Any ideas how to get this working using JS? Is it even possible? How does Doubleclick make this work for example?

For reference: this is the PHP code that successfully dropped the cookie

<?php 
$CookieName = "my3Pcookie";    // Cookie's name
$CookieValue = "hello, there"; // Cookie's value
$CookieDirectory = "/";        // Cookie directory ("/" for all directories)
$DaysCookieShallLast = 31;     // Days before expiration (decimal number okay.)


$lasting = ($DaysCookieShallLast<=0) ? "" : time()+($DaysCookieShallLast*24*60*60);
setcookie($CookieName,$CookieValue,$lasting,$CookieDirectory);

?>
Was it helpful?

Solution

Your problem is definitively based to the <img>-tag you're using. No JavaScript Code will be executed in an image.

The reason why it works if you do it by PHP is because the server is pre-processing your code at the time of requesting the file. Although this probably wont show you anything because you did not provide any valid image header.

If you would use the <iframe>-tag everything would work because the client can read and execute your JS-Code:

<iframe src='http://www.siteB.co.uk/cookie.php'></iframe>

But if you try to set the cookie by the <img>-tag you need to do it with a server-side language like PHP in this example.

Agencies like Doubleclick working with iframe, javascript snippets you sould insert into your page or|and a server-side solution.

Hope this helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top