Background: This question is in regards to an iFrame and its child document.
According to the MDN, HTMLIFrameElement.contentDocument when element.contentDocument
returns null
it indicates that JS considers that the document that contains the iFrame and the child document it references are not in the same origin.
If the iframe and the iframe’s parent document are Same Origin,
returns a Document (that is, the active document in the inline frame’s
nested browsing context), else returns null.
Same-origin policy indicates that two URLs have the same origin if they share the same “scheme/host/port tuple”.
Two URLs have the same origin if the protocol, port (if specified),
and host are the same for both.
However, in the simplified example below all of the documents are stored in the same root directory on my hard drive and accessed through an Express server.
Question: The variable interiorParagraph
in experiment.js
always ends up with the value null
instead of a reference to the document. I believe this indicates they aren’t in the same origin, but I’m not entirely certain because I haven’t been able to make any headway. Why am I not getting the result I expected?
Express:
const express = require('express');
const app = express();
const cors = require('cors');
const path = require('path');
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.use(express.static(path.join(__dirname, 'views/public')));
app.use(cors({ origin: '*' }));
app.get('/', (req, res) => {
res.render('index');
});
app.listen(8080, () => {
console.log('app listening');
});
index.ejs
<head>
<script src="/js/experiment.js" type="module" defer></script>
</head>
<body>
<iframe src="/html/interior.html" data-iframe></iframe>
</body>
interior.html
<body>
<p data-interior>Hello World</p>
</body>
experiment.js
const iframe = document.querySelector('[data-iframe]');
const interiorParagraph = iframe.contentDocument.querySelector('[data-interior]');
alert(interiorParagraph);