Why Links Inside an iframe srcdoc Resolve to Unexpected URLs

Debug relative links in iframe srcdoc previews. Learn how document base URLs, base elements, link targets, and sandbox restrictions affect navigation.

Published
Reading time
7 min read
Why Links Inside an iframe srcdoc Resolve to Unexpected URLs
On this page

A relative link inside an iframe with srcdoc can resolve to a different URL from the same link in a separately loaded HTML file. The key is the document’s base URL: srcdoc content normally uses the embedding document’s base URL as its fallback, while a loaded document normally uses its own URL.

This guide shows how to reproduce the difference, inspect the browser’s resolved URL, and account for <base>, sandboxing, and links intended to leave the frame.

Key Takeaways

  • For iframe srcdoc relative URL resolution, start by checking the embedding document’s base URL, not just the frame’s displayed about:srcdoc location.
  • A <base href> in the embedded document can change how its relative URLs resolve. A <base> in the parent can also affect the base inherited by srcdoc.
  • Resolving a URL and navigating to it are different steps. A sandbox, link target, browser policy, or user action can affect navigation after resolution.
  • Treat untrusted srcdoc HTML as active content. Sandboxing is useful, but it is not a substitute for sanitization and an appropriate isolation strategy.

Verification note: The HTML Living Standard was not available to consult for this article, and the examples were not run here. Check the current standard and your target browsers when behavior is critical, especially for sandbox and policy interactions.

Reproduce the difference

Create the following files in a local directory. The first frame uses srcdoc; the second loads a separate document. Both contain the same relative link.

index.html:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Frame URL resolution</title>
</head>
<body>
  <h1>Frame URL resolution</h1>

  <iframe
    title="Inline preview"
    srcdoc='<p><a href="guide.html">Open guide from srcdoc</a></p>'>
  </iframe>

  <iframe
    title="Loaded preview"
    src="preview/page.html">
  </iframe>
</body>
</html>

preview/page.html:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Loaded preview</title>
</head>
<body>
  <p><a href="guide.html">Open guide from loaded document</a></p>
</body>
</html>

From the directory containing index.html, start a local server, for example with Python installed:

python3 -m http.server 8000

Open http://localhost:8000/index.html. With no <base> element, the expected link destinations are:

  • srcdoc frame: http://localhost:8000/guide.html, resolved against the parent document’s base URL.
  • Loaded frame: http://localhost:8000/preview/guide.html, resolved against the loaded document’s URL.

The destination files are not included, so clicking a link may result in a 404. That still lets you inspect the requested path in the browser’s address or network tools. Alternatively, create a guide.html in each directory with distinguishable text.

A relative URL such as guide.html is resolved against a base URL; it is not automatically relative to the source file that generated the HTML string. The srcdoc frame’s document is associated with about:srcdoc, but that is not the useful fallback base for resolving these links. If the parent has its own <base href>, that can change the base used by the srcdoc document.

Advertisement

In browser developer tools, select the relevant frame’s execution context, then inspect the document and anchor:

const link = document.querySelector("a[href]");
console.log("Document base:", document.baseURI);
console.log("Attribute:", link?.getAttribute("href"));
console.log("Resolved URL:", link?.href);
console.log("Target:", link?.target);

getAttribute("href") shows the authored value; the anchor’s href property shows its resolved URL. document.baseURI helps identify the base used for that resolution. If the values look like those of the parent page, check that the console is using the frame’s context.

These checks do not prove where a click will ultimately navigate. Inspect the link’s target, iframe sandbox, relevant page policies, and any redirects as separate steps. Scripts or click handlers can also change the behavior. A URL parser can help examine components of a URL, but parsing alone cannot establish the browser’s effective navigation behavior.

Set an explicit base when the preview needs one

If the embedded HTML should resolve relative links under /preview/, add a base element to that document:

<iframe
  title="Preview with an explicit base"
  srcdoc='<!doctype html>
    <html lang="en">
    <head>
      <base href="/preview/">
    </head>
    <body>
      <p><a href="guide.html">Open guide</a></p>
    </body>
    </html>'>
</iframe>

Here, the expected destination for guide.html is /preview/guide.html on the base URL’s origin. An absolute href on <base> can make the intended origin and path clearer when the embedding page may appear at different locations.

Place the base element in the document’s head before URL-bearing elements. It can affect more than links, including relative image and stylesheet URLs, so check the whole preview after adding it. A page’s Content Security Policy can restrict which base URLs are accepted. If embedded markup is untrusted, do not let an attacker choose the base URL without validating or sanitizing it.

Another option is to generate absolute URLs for specific links. That avoids dependence on the document base for those links, but it still does not override navigation restrictions.

By default, a link without a different target navigates its own browsing context: inside the iframe. Choose a target deliberately when the reader should leave the preview:

  • target="_parent" targets the immediate parent browsing context.
  • target="_top" targets the top-level browsing context, which can be different from the immediate parent when frames are nested.
  • target="_blank" requests a new browsing context, subject to browser and sandbox restrictions. For links to external sites, explicitly using rel="noopener noreferrer" is a useful precaution.

For example, this link requests navigation of the top-level page:

<a href="/guide.html" target="_top">Open the guide</a>

A <base target> can set a default target for links that do not specify one, but it has document-wide consequences. Explicit targets are often easier to audit. Neither a target nor a correctly resolved URL guarantees navigation: sandbox restrictions, browser policies, user activation requirements, or the destination’s response can change the outcome.

Understand the sandbox boundary

An iframe with a sandbox attribute starts with restrictions; tokens selectively lift some of them. For example, a sandbox can prevent top-level navigation or new windows even when a link has the correct href and target.

  • allow-top-navigation-by-user-activation permits certain top-level navigations when triggered by user activation; allow-top-navigation grants broader top-navigation permission.
  • allow-popups permits popups in contexts where the browser otherwise allows them. allow-popups-to-escape-sandbox changes whether a newly opened context inherits sandbox restrictions.
  • allow-same-origin affects the embedded document’s origin treatment; it is not a way to set the document’s base URL. Without it, a sandboxed document receives an opaque origin.

Use the least permissive combination that supports the feature, and test actual clicks in the browsers you support. Avoid combining allow-scripts and allow-same-origin for same-origin untrusted content: that combination can undermine the sandbox boundary. A sandbox does not automatically prevent every external navigation or network request.

Advertisement

Security and accessibility for previews

If users can supply the embedded HTML, assume it may contain scripts, event handlers, forms, misleading links, and resource requests. Prefer displaying untrusted material as text when rendering HTML is unnecessary. When HTML rendering is required, sanitize it with a policy appropriate to the application, restrict allowed URLs and elements, and use sandboxing and other isolation controls as defense in depth. Assigning a string to srcdoc does not sanitize it.

Review whether links and embedded resources can lead users to untrusted destinations or disclose information through requests. Restrict iframe permissions and consider a separate origin and a suitable Content Security Policy for the preview architecture. Test the resulting policy rather than assuming it blocks every unwanted behavior.

Give each iframe a meaningful title, as in the examples, so assistive-technology users can identify it. Use descriptive link text and make it clear when a link opens a new tab or takes the user out of the preview. Check keyboard navigation and focus behavior in the supported browser and assistive-technology combinations.

Common Mistakes

  • Resolving against about:srcdoc: Inspect document.baseURI and the parent’s base instead.
  • Looking only at the literal href: Compare the attribute with the resolved href property.
  • Treating allow-same-origin as a URL fix: Origin permissions and relative URL resolution address different questions.
  • Assuming target="_top" bypasses a sandbox: The target expresses an intent; sandbox permissions and user activation can still matter.
  • Adding <base> without checking other resources: Images, stylesheets, and other relative URLs may change too.
  • Treating a parser or sandbox as complete protection: Validate and sanitize untrusted content, then test the actual browser behavior.

Best Practices

  1. Reproduce the issue with one link and record the parent URL, the frame’s document.baseURI, the authored href, and the resolved href.
  2. Decide whether the preview should inherit the parent’s base or use an explicit, trusted base. Verify all affected resources after the change.
  3. Decide separately where links should open, then configure targets and the minimum necessary sandbox permissions.
  4. Test ordinary links, external links, nested frames, and blocked navigation in the browsers and embedding environments you support.

Conclusion

A srcdoc preview is inline HTML, not a normally loaded file at the location you may have imagined for it. Inspect its effective base URL first; then debug target and sandbox behavior separately. That distinction makes unexpected link destinations much easier to diagnose.

What would your domain sell for?

A free TidyURLs account unlocks the Domain Estimator. It prices a name from 191,011 real domain sales.