1. 事前準備
您應透過私人嵌入或單一登入 (SSO) 嵌入,將 Looker 內容嵌入 iframe 中。在本程式碼研究室中,我們將透過 JavaScript 與 iframe 互動,讓網頁更具動態效果。網頁會與 iframe 內嵌的 Looker 內容互傳訊息。
必要條件
- 擁有正在執行的 Looker 執行個體
- 在 iframe 中私下嵌入或透過單一登入 (SSO) 嵌入 Looker 資訊主頁
- 瞭解 window.postMessage() 方法
課程內容
- 如何準備 iframe 和 Looker 執行個體,以進行 JavaScript 互動
- 如何監聽 iframe 中的事件
- 如何將動作訊息傳送至 iframe
軟硬體需求
- 可存取管理 iframe 的前端程式碼 HTML 和 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>
如果您使用 SSO 嵌入,請將網域新增為 嵌入網址的 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 內容事件,並傳送動作。如需更多資訊,請參閱下列資源: