Getting document.URL

Is there a way to get the value of document.URL from a notebook? I am getting a value that’s different from the one displayed in the browser’s address bar, as can be seen in this notebook:

Similar problems are encountered also with location.href or location.

My intent was to read the value of location.hash into a cell value.

1 Like

document.URL and the other approaches you’re using will fail because Observable notebooks run in an iframe. I don’t see an easy way to read the URL of the containing page since that is likely to go against the same-origin policy. E.g. window.parent.location.href returns SecurityError: Permission denied to get property "href" on cross-origin object. Actually, see below!

Edit: Oh, I just realized that you said you only want the location.hash. If you’re planning to parse that info and use it as user-provided data in your notebook, an alternate approach is to use the query parameters (stuff after ? in the URL) as shown in these notebooks:

EDIT 2: Hmm, the notebooks above provide a solution to part of the original question: document.baseURI will return the URL of the containing page, but unfortunately it does not seem to contain the URL hash…

2 Likes

This should work:

Object.assign(document.createElement("a"), {href: ""}).hash

Edit: actually it won’t because we don’t pass the hash down to the worker. So, you’ll need to use the query string, at least for now.

Just for reference, the shortest way (I know of) to obtain the notebook URL would be:

html`<a href>`.href
4 Likes

Thank you all for your quick and thorough help :slight_smile:

So until the hash is made visible to the worker, there is no solution.

I’ll go with query strings for now, then I’ll switch to hash URIs when exporting the code outside Observable.

Thanks again, and keep up the great work!

1 Like

Thanks for the request!

We now pass down query strings and hash parts of the URL from the parent to the worker, so you should be able to do this.

Here’s a quick demonstration notebook:

Good luck!

2 Likes

Thank you for the solution! Sorry for coming back to you this late ^_^’

This community is fantastic btw. :smiley:

3 Likes