let url = (content, type) => URL.createObjectURL ( new Blob ([content], {type})); let cssUrl = url ('#d1 { color: green; }', 'text/css'); let htmlUrl = url (` <link rel=stylesheet href=${cssUrl}> <div id=d1>Div</div>`, 'text/html'); ifr.src = htmlUrl; log.textContent = cssUrl; <iframe id=ifr></iframe> <br> <span id=log></span>

This code works fine in jsfiddle

cssUrl is something like: blob:https://fiddle.jshell.net/2dacb344-cec1-47f5-b009-9093a2680922

But not as a local file (css is not applied, though content is displayed fine) when opened in browser (without server) or in stackoverflow.

In this case cssUrl looks like this: blob:null/37686c99-658b-4c13-883d-3f0a3fc4937b

How to fix this so that it works in local file?

Venkata Raju's user avatar

6

The issue is that your file: origin is considered an opaque origin. This is a security measure which allows to have multiple files from the same directory open in different tabs without them being able to communicate and prevents scripts from reading the content of other files in the directory.
In a usual http[s]: case, any page on the same origin should be able to access its content, but this opaque origin means that the blob: URL isn't linked to any document anymore, not even the one that created it.

What you can do in your case is to use a data: URL rather than a blob: URL. These URLs do contain the whole data and don't require an actual fetch to occur, bypassing the origin issue:

let url = (content, type) => `data:${type},${encodeURIComponent(content)}`; let cssUrl = url ('#d1 { color: green; }', 'text/css'); let htmlUrl = url (` <link rel=stylesheet href=${cssUrl}> <div id=d1>Div</div>`, 'text/html'); ifr.src = htmlUrl; log.textContent = cssUrl; <iframe id=ifr></iframe> <br> <span id=log></span>

StackSnippet's null origined iframes expose the same behavior

Since this uses a string representation, you may meet the string's max size limitation (~500MB in V8 x64)

Kaiido's user avatar

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.