Hey @igor_g, this is because we want to ensure that the receiver has the same origin as the sender; passing the parent.location.origin would kind of defeat this purpose. (In principle, at least – accessing the parent from within an iframe is only possible if both sides have the same origin anyway.)
I have another one question. Do you know about resources loading in JS? How it should work? For example could I get the URL of current JS-script within this script? I mean something like…
function Foo()
{
console.log(this.location) // print out '/js/library/tools/foo.js'
}
Hm… you mean something like this? It boils down to querying for all scripts present on the page, where the last script is the one currently being executed:
// Assuming we have 3 scripts foo.js, bar.js and baz.js
// included in that order, the next line would yield:
// [<script src="foo.js">] for foo.js
// [<script src="foo.js">, <script src="bar.js">] for bar.js
// [<script src="foo.js">, <script src="bar.js">, <script src="baz.js">] for baz.js
const scripts = document.querySelectorAll('script')
const srcURL = new URL(scripts[scripts.length - 1].src)
console.log(srcURL.pathname)
This would only work when run immediately though, not asynchronously at some later point when further scripts might have been added to the DOM. Also I’m not sure how robust this solution is with regard to deferred scripts, say.
Tricky. :-) Off the top of my head I’d think we might install a service worker that keeps track of the scripts being loaded… but then again we’d still need some sort of ID to get the request details for a given script, so we might just as well assign a DOM ID from the first:
Either way, the script would need to know its ID… I don’t think there’s a completely generic solution to this, but I’ll give it some thought tomorrow or so (I’m leaving the house right now).
Could service worker recognize loaded script without ID?
Yes, if script has ID, this solving the problem… But it is not internal JS-library solution. Developer should obligatory set ID to some script, and if not, this causes error… Not really elegant.
Turns out there’s actually document.currentScript, which seems to do the same as the above snippet with the same limitations regarding callbacks. I don’t see an immediate problem here though – just store a reference at the top of your script and you can then use it anywhere: