Guide to Dynamically Changing Embed URLs
In embedding scenarios, it is often necessary to dynamically modify the embedded page URL based on business and interaction requirements. To address this need, HENGSHI SENSE supports the following two methods for dynamically changing the URL of the embedded iFrame.
PostMessage
During the embedding process, you can use PostMessage to dynamically modify the URL of the embedded page. This supports both hs_urlpush
and hs_urlchange
methods. Using PostMessage to dynamically modify the embedded page URL does not cause the page to reload.
URL push
Below is an example of using the hs_urlpush
method to dynamically change the page URL in PostMessage.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Local Test</title>
<style>
h2 {
font-size: 16px;
font-weight: normal;
color: #999;
}
h2 i {
color: #333;
}
</style>
</head>
<body>
<button onClick="onUrlFilterChange()">Send Event</button>
<iframe
allowFullScreen="true"
width="1280"
height="800"
frameborder="0"
id="iframe"
src="http://192.168.2.243:9998/share/2351A2F5/infographic/46CA0B3B">
</iframe>
<script>
var $iframe = document.getElementById('iframe');
function onUrlFilterChange() {
var pathname = '/share/2351A2F5/infographic/46CA0B3B';
var search = `?where=[{"field":{"fieldName":"_c6","dataset":39713,"label":"time","type":"date"},"dataset":39713,"kind":"function","op":"in","args":[{"kind":"function","op":"dow","args":[{"kind":"field","op":"_c6","dataset":39713}]},{"kind":"constant","op":[${randomNumber(1, 7)}, ${randomNumber(1, 7)}]}]}]`;
$iframe.contentWindow.postMessage(JSON.stringify({
event: 'dispatchCustomEvent',
data: ['hs_urlpush', {
pathname: pathname,
search: search,
}],
}), '*');
}
function randomNumber(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
</script>
</body>
</html>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
URL Change
The system also supports dynamically modifying the page URL using the hs_urlchange
method in PostMessage. Refer to the example below.
// After JSON.parse(event.data):
{
event: 'HengshiInteractiveEvent',
data: {
event: 'hs_urlchange',
data: {
pathname: '/app/xxx?aa=bb',
search: '?aa=bb'
query: {
aa: 'bb',
},
},
},
}
2
3
4
5
6
7
8
9
10
11
12
13
14
Directly Modify iframe.src
You can achieve dynamic changes to the embedded page URL by directly editing the iframe URL. This method has the same effect as using contentWindow.postMessage
, but it will cause the page to reload, which may slightly impact performance.
$iframe.src = 'https://preview.hengshi.com' + pathname + search;