mockplus.showUI()函數(shù)可顯示插件的用戶界面,使用此函數(shù)的最簡單方法是執(zhí)行以下操作:
1. 創(chuàng)建一個包含 UI 標記的 HTML 文件;
2. 更改manifest.json, 使其包含"ui": "ui.html", 其中"ui.html"是你的HTML文件的文件名;
3. 在你的插件代碼中添加以下調(diào)用:
mockplus.showUI(__html__, { visible: true, width: 400, height: 400, title: '我的摹客DT插件', });
這會在DT的<iframe>中顯示你的 HTML 文件的內(nèi)容。
1. 從 UI 向插件代碼發(fā)送消息
需要從 UI 向插件代碼發(fā)送消息,請在 HTML 中編寫以下內(nèi)容:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>first-dt-plugin</title> </head> <body> <button id="messageButton">發(fā)送消息</button> </body> <script> document.getElementById("messageButton").addEventListener("click", () => { window.parent.postMessage( { pluginMessage: { type: "pluginMessage", clickButton: "messageButton", }, }, "*" ); }); </script> </html>
需要接收插件代碼中的消息,請編寫以下內(nèi)容:
mockplus.ui.onmessage = (message) => { const pluginMessage = message.pluginMessage; const type = pluginMessage?.type; switch (type) { case 'pluginMessage': { console.log('接收到的插件消息', pluginMessage.clickButton); break; } default: console.log('接收到的其他消息'); break; } };
2. 從插件代碼向 UI 發(fā)送消息
需要從插件代碼向UI發(fā)送消息,請編寫以下內(nèi)容:
mockplus.ui.onmessage = (message) => { const pluginMessage = message.pluginMessage; const type = pluginMessage?.type; switch (type) { case 'pluginMessage': { mockplus.ui.postMessage('接收到了消息', { origin: '*' }); break; } default: console.log('接收到的消息'); break; } };
需要接收 UI 中的消息,請在 HTML 中編寫以下內(nèi)容:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>first-dt-plugin</title> </head> <script> window.onmessage = ({ data }) => { console.log("接收到的信息", data); }; </script> </html>
注:目前不支持發(fā)送除基礎(chǔ)數(shù)據(jù)結(jié)構(gòu)以外的對象,如Uint8Array對象, Blob對象、ArrayBuffers 或TypedArray對象。