Skip to content

Commit 7eba3c0

Browse files
committed
Refactor getDataFromUrl (less specific to domains, add error logging)
1 parent 05dc8e0 commit 7eba3c0

File tree

2 files changed

+18
-17
lines changed

2 files changed

+18
-17
lines changed
Lines changed: 12 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,16 @@
11
export default function getDataFromUrl(target: HTMLElement): Record<string, string> {
2-
let url: URL;
3-
if (
4-
// SvelteKit DEV mode, preview server, or static hosting:
5-
import.meta.env.DEV ||
6-
window.location.origin === 'http://localhost:4173' ||
7-
window.location.origin === 'https://static.datenhub.net' ||
8-
window.location.href.includes('apidata.googleusercontent.com') ||
9-
window.location.href.includes('storage.googleapis.com')
10-
) {
2+
const parent = target.parentNode?.parentNode as HTMLElement | null;
3+
4+
// Default: Embedded mode – use URL used to embed the component
5+
// `data-url` is the embeds the grandparent element, provided by Sophora
6+
let embedURL = parent?.dataset.url;
7+
8+
if (!embedURL) {
119
// Preview mode – use URL of current page
12-
url = new URL(window.location.href);
13-
} else {
14-
// Embedded mode – use URL used to embed the component
15-
// `data-url` is set on the grandparent element, provided by Sophora
16-
const parent = target.parentNode?.parentNode as HTMLElement | null;
17-
url = new URL(parent?.dataset.url || '');
10+
embedURL = window?.location.href;
1811
}
19-
const params: Record<string, string> = Object.fromEntries(url.searchParams);
20-
return params;
12+
13+
return URL.canParse(embedURL)
14+
? Object.fromEntries(new URL(embedURL).searchParams.entries())
15+
: (console.error('Could not parse Embed-URL:', embedURL), {});
2116
}

sophora-components/src/routes/datawrapper-switcher/DatawrapperSwitcher.svelte

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,19 +10,25 @@
1010
let fixedHeight = $state(null);
1111
let layout = $state('auto');
1212
13+
let url = $state('');
14+
1315
onMount(() => {
1416
const entries = getDataFromUrl(root);
1517
labels = entries.labels.split(',') || [];
1618
ids = entries.ids.split(',') || [];
1719
fixedHeight = entries.fixedHeight || null;
1820
layout = entries.layout || 'auto';
21+
22+
url = window.location?.href;
1923
});
2024
</script>
2125
2226
<div class="datawrapper-switcher" bind:this={root}>
2327
<DesignTokens theme="auto">
2428
<h1>Datawrapper switcher to be rendered here:</h1>
2529
<pre>{JSON.stringify({ labels, ids, fixedHeight, layout }, null, 2)}</pre>
30+
<pre>dataset url: {root?.parentNode?.parentNode?.dataset.url || 'n/a'}</pre>
31+
<pre>actual url: {url || 'n/a'}</pre>
2632
2733
<!-- <Switcher
2834
options={labels}

0 commit comments

Comments
 (0)