JavaScript Document domain Property

Beginner
⏱️ 12 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Deprecated
Instance property

What You’ll Learn

Document.domain is a deprecated instance property that gets or sets the domain portion of the origin for same-origin checks. Learn what the getter returns, why the setter is unsafe, safer alternatives, and five examples with try-it labs.

01

Kind

Get / set

02

Type

string

03

Status

Deprecated

04

Read via

location.hostname

05

Talk via

postMessage

06

Risk

Setter unsafe

Introduction

Browsers isolate pages with the same-origin policy. An origin is roughly scheme + host + port (for example https://a.example.com:443). Two pages can normally read each other’s DOM only if they share that origin.

Historically, sites on a.example.com and b.example.com sometimes set document.domain = "example.com" so both pages shared a relaxed domain and could access each other’s DOM. MDN now deprecates that pattern because it is hard to reason about and easy to get dangerously wrong.

💡
Modern replacements

Read the host with location.hostname. For cross-window talk, use postMessage. Do not open your whole DOM to every sibling subdomain.

Related Document tutorials: documentURI, cookie, Document constructor.

Understanding Document.domain

An instance property on Document that gets/sets the domain portion of the origin (MDN).

  • Getter — usually the hostname; empty string for opaque origins (e.g. some data: pages); returns the set value if the setter was used (MDN).
  • Setter — may relax same-origin rules to a parent domain; deprecated and dangerous (MDN).
  • Limits — only same hostname or a parent domain; otherwise SecurityError.
  • Not a no-op — even document.domain = document.domain changes origin accounting (MDN).
  • Incomplete — does not unlock all APIs (e.g. some storage / worker checks still use the real origin) (MDN).

📝 Syntax

JavaScript
// Read (legacy — prefer location.hostname)
document.domain

// Write (deprecated — do not use in new code)
document.domain = "example.com";

Value

A string representing the domain portion of the origin (MDN).

Preferred read

JavaScript
const currentHostname = location.hostname;
// Avoid document.domain entirely for new code (MDN)

🔒 Why the setter is deprecated (MDN)

  • Undermines same-origin protections and complicates browser origin models.
  • Can grant full DOM access across subdomains—often broader than intended.
  • Removes the port component from the origin model; other ports on the same host may gain access.
  • Especially insecure on shared hosting (same IP / sibling subdomains).
  • May do nothing with modern isolation headers (COOP/COEP, Origin-Agent-Cluster).
  • Does not fully unlock APIs such as localStorage, IndexedDB, BroadcastChannel, SharedWorker for subdomain access (MDN).

⚡ Quick Reference

GoalCode / note
Read host (modern)location.hostname
Read originlocation.origin
Legacy readdocument.domain (avoid new use)
Cross-origin talkotherWindow.postMessage(data, targetOrigin)
Do notSet document.domain to “share” DOM
MDN statusDeprecated

🔍 At a Glance

Four facts about document.domain.

Type
string

Domain

Access
get + set

Setter bad

Status
deprecated

MDN

Prefer
hostname

+ postMessage

📋 Setter failures (SecurityError)

Situation (MDN)Result
Sandboxed iframe / documentThrows SecurityError
No browsing contextThrows
Effective domain is nullThrows
Value not same host or parent domainThrows (e.g. set example.org on example.com)
Cross-origin / origin isolated pagesMay do nothing (deprecation + isolation)

Examples Gallery

Examples follow MDN Document: domain. Prefer the modern alternatives. Use View Output or Try It Yourself for each case.

📚 Getting Started

See the legacy getter, then switch to location.hostname.

Example 1 — Get document.domain (MDN)

On https://developer.mozilla.org/..., this would be "developer.mozilla.org".

JavaScript
const currentDomain = document.domain;
console.log(currentDomain);
// Often the hostname, or "" for opaque origins
Try It Yourself

How It Works

Useful only for understanding legacy pages. New code should not depend on this getter.

Example 2 — Prefer location.hostname (MDN)

MDN’s recommended way to avoid document.domain entirely.

JavaScript
const currentHostname = location.hostname;
console.log(currentHostname);
// Same host string for normal https pages, without using document.domain
Try It Yourself

How It Works

Also consider location.host (includes port) and location.origin (full origin).

📈 Compare, Failures & Safer Messaging

Side-by-side reads, SecurityError demos, and postMessage.

Example 3 — domain vs hostname vs host vs origin

See how the strings differ on a normal page.

JavaScript
console.log("document.domain:", document.domain);
console.log("location.hostname:", location.hostname);
console.log("location.host:", location.host);
console.log("location.origin:", location.origin);
Try It Yourself

How It Works

On non-default ports, host includes the port while hostname does not.

Example 4 — Invalid Setter Throws SecurityError (MDN)

Educational only: setting a foreign domain fails.

JavaScript
try {
  // On https://example.com this throws (MDN last failure case)
  document.domain = "example.org";
  console.log("Unexpectedly set");
} catch (err) {
  console.log(err.name); // "SecurityError"
}
Try It Yourself

How It Works

Do not “fix” this by finding a parent domain that works—leave the setter unused in production.

Example 5 — Safer Pattern: postMessage (MDN)

Sketch of controlled cross-origin messaging instead of document.domain.

JavaScript
// Parent page talking to a known iframe origin:
const frame = document.querySelector("iframe");
frame.contentWindow.postMessage(
  { type: "ping", text: "hello" },
  "https://trusted.example.com" // always specify targetOrigin
);

window.addEventListener("message", (event) => {
  if (event.origin !== "https://trusted.example.com") return;
  console.log("Got:", event.data);
});
Try It Yourself

How It Works

MDN: controlled access via message-passing is much more secure than blanket DOM exposure from document.domain.

🚀 Common Use Cases

  • Legacy maintenance — recognize old subdomain “sharing” scripts.
  • Migration — replace setters with postMessage or same-origin backends.
  • Teaching same-origin — show why relaxing domain is risky.
  • Not for new features — MDN: avoid using it; update existing code.
  • Host display — use location.hostname, not document.domain.
  • Security reviews — flag any document.domain = as a smell.

🧠 Old Pattern vs Modern Pattern

1

Legacy: two subdomains

a.example.com and b.example.com needed DOM access.

Old need
2

Legacy: set document.domain

Both set "example.com" and shared a relaxed domain (deprecated).

Unsafe
3

Modern: keep origins separate

Do not broaden DOM access across the whole parent domain.

Isolate
4

Modern: postMessage (or same-origin APIs)

Send only the data you intend, to a checked targetOrigin.

📝 Notes

  • MDN: Deprecated — Deprecated banner shown above; not Experimental / Non-standard.
  • Prefer location.hostname for reading the host (MDN).
  • Prefer postMessage instead of the setter (MDN).
  • Opaque origins may yield an empty string from the getter.
  • Related: documentURI, cookie, Document constructor.

Legacy / Deprecated Support

Document.domain is deprecated on MDN. It may still exist for compatibility, but the setter is unsafe and should not be used in new code. Logos use the shared browser-image-sprite.png sprite from this project.

Deprecated · Avoid setter

Document.domain

Deprecated domain getter/setter for same-origin policy — prefer location.hostname and postMessage.

Legacy Compatibility only
Google Chrome May still expose · setter discouraged
Legacy / limited
Mozilla Firefox Legacy support · prefer alternatives
Legacy / limited
Apple Safari Do not rely on setter behavior
Legacy / limited
Microsoft Edge Chromium · avoid new use
Legacy / limited
Opera Follow Chromium deprecation path
Legacy / limited
Internet Explorer Legacy same-origin domain API
Legacy support
Document.domain Avoid in new code

Bottom line: Recognize document.domain in old scripts. For new work, read hosts with location.hostname and communicate across origins with postMessage — never relax origins with document.domain.

Conclusion

Document.domain is a deprecated way to read or relax the domain used in same-origin checks. Learn it to maintain old code—then migrate to location.hostname and postMessage.

Continue with embeds, documentURI, cookie, or the JavaScript hub.

💡 Best Practices

✅ Do

  • Use location.hostname / origin for reads
  • Use postMessage with an explicit targetOrigin
  • Validate event.origin on incoming messages
  • Treat any document.domain = as tech debt
  • Keep sibling apps same-origin via routing when possible

❌ Don’t

  • Set document.domain in new features
  • Assume setting domain unlocks storage / workers (MDN)
  • Use "*" as postMessage target casually
  • Ignore shared-hosting risks of domain relaxation
  • Think document.domain = document.domain is harmless (MDN)

Key Takeaways

Knowledge Unlocked

Five things to remember about document.domain

Deprecated same-origin domain API — prefer hostname and postMessage.

5
Core concepts
📄02

Type

string

API
🔒03

Setter

unsafe

Security
🌐04

Read

hostname

Prefer
💬05

Talk

postMessage

Modern

❓ Frequently Asked Questions

It gets or sets the domain portion of the document's origin used by the same-origin policy. The getter usually returns the hostname; the setter was historically used to relax subdomain boundaries.
Yes. MDN marks Document.domain deprecated. Avoid it in new code. Prefer location.hostname to read the host, and Window.postMessage for controlled cross-origin communication.
MDN: the getter is not dangerous in the same way as the setter, but location.hostname is simpler and lets you avoid document.domain entirely.
MDN: it undermines same-origin protections, can expose the DOM across subdomains, drops the port from the origin model, and is especially risky on shared hosting.
Use Window.postMessage to send asynchronous messages between origins. That controlled message-passing is much safer than blanket DOM access via document.domain (MDN).
MDN: a SecurityError DOMException for sandboxed documents, no browsing context, null effective domain, or values that are not the current hostname or a parent domain.
Did you know?

Setting document.domain to its current value is still an origin-changing operation (MDN). Pages that “touch” document.domain can become cross-origin relative to sibling pages that never did—another reason the API is a footgun.

Next: embeds

Learn the live HTMLCollection of every <embed> in the document.

embeds →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful