Setting third party cookie by using 1x1 <img> tag - Javascript doesn't drop cookie

烂漫一生 提交于 2019-12-13 13:22:58

问题


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);

?>

回答1:


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.



来源:https://stackoverflow.com/questions/14415860/setting-third-party-cookie-by-using-1x1-img-tag-javascript-doesnt-drop-cook

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!