1. 准备工作
您应该通过私密嵌入或 SSO 嵌入将 Looker 内容嵌入到 iframe 中。在此 Codelab 中,我们将通过 JavaScript 与您的 iframe 互动,让您的网页更具动态性。您的网页将向 iframe 嵌入的 Looker 内容发送消息,并接收来自该内容的消息。
前提条件
- 拥有一个正在运行的 Looker 实例
- 在 iframe 中私密嵌入或单点登录嵌入 Looker 信息中心
- 了解 window.postMessage() 方法
学习内容
- 如何准备 iframe 和 Looker 实例以进行 JavaScript 互动
- 如何监听 iframe 中的事件
- 如何向 iframe 发送操作消息
所需条件
- 访问前端代码的 HTML 和用于管理 iframe 的 JavaScript
- 访问 Looker 实例中的管理员嵌入设置
2. 准备工作
您需要先准备 iframe 和 Looker 实例,然后才能与 iframe 互动。
向 iframe 添加 id
属性
您需要验证来自 iframe 的消息。为此,请在 iframe 上定义 id
属性:
<iframe
id="looker"
src="https://instance_name.looker.com/embed/dashboards/1"
>
</iframe>
将嵌入的网域添加到 iframe 的 src
属性
确定托管 iframe 的网页的网域。假设网页的网址为 https://mywebsite.com/with/embed
,则网页的域名为 https://mywebsite.com
。
如果您使用的是不公开嵌入,请在 iframe 的 src 中将该网域添加为 embed_domain
查询参数:
<iframe
id="looker"
src="https://instance_name.looker.com/embed/dashboards/1?embed_domain=https://mywebsite.com"
>
</iframe>
如果您使用的是单点登录嵌入,请将该网域作为 embed_domain
查询参数添加到嵌入网址。
在 Looker 实例中将嵌入的网域列入许可名单
最后,您需要在 Looker 实例中将嵌入的网域列入许可名单,以允许发送消息。
前往 Looker 实例的管理部分中的嵌入页面。https://your_instance.looker.com/admin/embed
在 Embedded Domain Allowlist 字段中,输入嵌入的网域。输入域名后,按 Tab 键,使域名显示在一个框中。请勿添加尾部斜杠 /
。
选择更新按钮。
3. 监听来自 iframe 的事件消息
嵌入了 Looker 内容的 iframe 会向其托管网页发送消息。这些事件消息包含有关嵌入的 Looker 内容的及时信息,例如,嵌入式信息中心是否已开始加载,或者用户是否在嵌入的内容中选择了“下载”选项。我们来接收并解析这些事件。
了解事件对象架构
该事件对象的架构如下:
{
type: "...",
eventSpecificProperty1: ...,
eventSpecificProperty2: ...,
...
}
该事件始终具有 type
属性,可让您确定它是哪种事件。所有其他事件专用属性均在我们的事件参考文档中定义。
接收并解析事件
将以下代码添加到网页的 JavaScript 初始化或管理 iframe 的位置:
window.addEventListener("message", function(message) {
const iframeElement = document.getElementById("looker");
if (message.source === iframeElement.contentWindow) {
if (message.origin === "https://instance_name.looker.com") {
const event = JSON.parse(message.data);
switch (event.type):
case "dashboard:run:start":
console.log("The embedded dashboard has started loading");
}
}
});
该代码段将执行以下操作:
- 监听
window
对象中的"message"
事件。 - 检查消息的
source
属性是否为包含嵌入式 Looker 内容的 iframe。 - 检查消息的
origin
属性是否为 Looker 实例的网域。 - JSON 会解析消息的
data
属性,以访问和解析事件对象。 - 开启事件对象的
type
属性,以确定该事件是哪个事件并对其执行操作。
现在,您的托管网页可以动态响应嵌入的 Looker 内容发出的事件!
4. 向 iframe 发送操作消息
托管网页还可以向 iframe 的嵌入式 Looker 内容发送消息。这些操作消息可能会更改嵌入式 Looker 内容的状态,例如更新嵌入式信息中心内的过滤条件。我们来创建一个操作消息,告知嵌入式信息中心运行其查询并将消息发送到您的 iframe。
创建操作消息
在网页的 JavaScript 中创建操作消息:
const action = { type: "dashboard:run" };
const actionJSONFormatted = JSON.stringify(action);
action
对象的格式与之前的 event
对象相同。它始终包含 type
属性,然后是操作参考文档中定义的操作专用属性。操作消息必须采用 JSON 格式。
发送操作消息
在网页的 JavaScript 中,将 JSON 格式的操作发送到 iframe:
const iframeElement = document.getElementById("looker");
iframeElement.contentWindow.postMessage(actionJSONFormatted, 'https://instance_name.looker.com');
- 确定您要向其发送操作的 iframe。
- 对 iframe 的
contentWindow
属性调用postMessage()
方法以发送消息。
现在,您的托管网页可以动态更改嵌入的 Looker 内容的状态!
5. 其他信息
恭喜!您现在可以监听来自 iframe 嵌入的 Looker 内容的事件,并将操作发送到 iframe 的嵌入式 Looker 内容。如需了解详情,请参阅以下资源: