Can advertisements read cookies of the website it is on?

Any script included into a page can read all cookies for which the httpOnly attribute is not set. Access restrictions for scripts are not determined based on the domain the script was loaded from but only in which page it is loaded into. This means all scripts loaded into a page have the same access and control over this page, no matter what the origin of the script was. Regarding cookies this means that you need to protect any sensitive cookies like session ids with httpOnly if you have included third party scripts which are outside of your control and trust into your page.

But including such scripts into a page working with sensitive data is a bad idea anyway, since such scripts can not only read cookies (unless httpOnly) but also extract information from forms (like login credentials) or change the client side application logic. See also Should I be worried of tracking domains on a banking website?.

Note that these statements apply only to third party script which is directly included into the main page. If the script is instead only inside a third party iframe inside the main page it can neither read cookies on the main page nor access or modify the DOM on it.


Each cookie belongs to a domain (an origin). Every modern browser implements a same-origin policy which prevents a script from accessing cookies of an origin that's different from the one running the script (with some workarounds for subdomains).

If so, what stops them from reading the session id to perform session hijacking?

If somesite.example implements an advertising script this way...

<script src="https://rogueadvertisement.example/script.js"></script>

...nothing prevents the script from accessing and modifying a cookie on somesite.example, unless the cookie has the HttpOnly flag set. (This flag denies access to a cookie for all client scripts and makes it only available via HTTP response header.) That's because an embedded script is run on the origin of the embedding site.

If somesite.example embeds a third-party advertisement in a frame...

<iframe src="https://rogueadvertisement.example/ad.html"></iframe>

...the embedded document has its own origin and scripts running inside the frame cannot access cookies that belong to the parent document's domain.

Also, there are some knobs to make embedding potentially untrusted sources even safer, such as the HTML5 sandbox attribute. Using it as an empty attribute...

<iframe sandbox src="https://rogueadvertisement.example/ad.html"></iframe>

... enforces various additional restrictions such as denying any scripts being run inside the frame.