window.open Basics

A clarification on window.open URLs, relative vs absolute paths, dev vs build behavior, and why both may ‘work’ during development.

Apr 2, 2020 · 2 min read · 267 Words · -Views -Comments · Programming
JavaScript 🇨🇳 阅读中文版
Read with AI

Choose an AI assistant

ChatGPT Open in a new tab with the article link and prompt
Claude Copy the prompt, then open Claude

Open Claude
Trouble reading the article?

If the prompt is missing, copy the full prompt below into your AI assistant. If the AI cannot read the article, paste the visible passage you want to discuss and add your question.

window.open loads a new resource. We typically open a web URL. During code review I saw this:

window.open('../../static/template.xlsx')

Project structure:


│── home
│       └── banner
│           └── index.tsx
└── static 
    └── template.xlsx

This is problematic. After build, static is top-level. The correct path should be static/template.xlsx.

But the key point: I thought this wouldn’t work locally since it’s not a proper web path but a project path. Yet it did work—revealing a gap in my understanding. Notes below.

  1. URL

    A Uniform Resource Locator (URL) is a reference to a web resource that specifies its location and a retrieval mechanism. A URL is a specific type of URI. URLs most commonly reference web pages (http), but also ftp, mailto, JDBC, etc.

    A URL can address static or dynamic resources.

  2. URLs can be relative or absolute

    You can use .. and the browser resolves relative paths to absolute ones.

    These two URLs are equivalent, note the ../ in the second:

https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/r/www/cache/static/protocol/https/soutu/img/camera_new_x2_fb6c085.png

https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/r/www/cache/../cache/static/protocol/https/soutu/img/camera_new_x2_fb6c085.png

```
  1. Why both dev and build paths “work” in development

    3.1 The local Webpack dev server exposes the project as a web service without restrictions, so localhost:3000/** is routable. Production hosting often adds security restrictions.

    3.2 In dev, TypeScript files exist as separate files. Webpack can resolve ../../static/template.xlsx, so it “works”.

In dev, static/template.xlsx “works” even though it’s not the real dev file path because of CopyWebpackPlugin:

```javascript
new CopyWebpackPlugin([
...
  { from: './src/main/webapp/static/', to: 'static' },
...
])
```

Final Thoughts

  1. The original path was wrong, but with loaders/plugins auto-handling assets, it may still work—similar to CSS-in-JS pipelines.
  2. Use small details like this to reinforce understanding.
Authors
Developer, digital product enthusiast, tinkerer, sharer, open source lover