# 事件通信示例

本示例主要简单演示第三方应用如何使用事件通信,事件详细描述请参考 模块通信事件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>扩展模块通信Demo</title>
    <style>
        .main { position: absolute; left: 45%; top: 40%; }
        .btn-primary { width: 150px; height: 40px; border-radius: 4px; color: #fff; background-color: #409eff; border-color: transparent; display: block; margin-top: 10px; }
        .btn-primary:hover { background-color: #3582fb; }
    </style>
</head>
<body>

<div class="main">
    <button class="btn-primary" onclick="onShowDialogClick()">TestShowDialog</button>
    <button class="btn-primary" onclick="onShowConfirmClick()">TestShowConfirm</button>
    <button class="btn-primary" onclick="onSyncUrlClick()">TestSyncUrl</button>
</div>

</body>

<script>
    function init() {
        window.addEventListener("message", handleMessage);
    }

    function handleMessage(event) {
        console.log('Third-Party-App Received:', event);

        if (!event.data || !event.data.event || !event.data.code) {
            return;
        }

        switch (event.data.event) {
            case 'confirmYes':
                // 收到用户点击 Tapd 系统确认框的【确定】按钮事件
                // 第三方应用处理
                break;
            default:
                break;
        }
    }

    function getQueryVariable(variable) {
        const query = window.location.search.substring(1);
        const vars = query.split("&");
        for (let i = 0; i < vars.length; i++) {
            const pair = vars[i].split("=");
            if (pair[0] === variable) {
                return pair[1];
            }
        }
        return false;
    }

    function sendMessage(event, params) {
        const config = {
            event: event,
            params: params,
            code: getQueryVariable('code'),
        }
        console.log('Third-Party-App Send:', config);
        window.parent.postMessage(config, '*');
    }

    function onShowDialogClick() {
        sendMessage('showDialog', {
            title: 'TestShowDialog',
            url: 'https://qq.com',
            height: 800,
            width: 800,
            showBtn: true,
            btnYesText: "确定",
            btnNoText: "取消",
        });
    }

    function onShowConfirmClick() {
        sendMessage('showConfirm', {
            content: 'TestShowConfirm',
            data: {value: 'test-show-confirm'},
        });
    }

    function onSyncUrlClick() {
        sendMessage('syncUrl', {
            url: '#urlhash',
            refresh: false,
        });
    }
    
    init();
</script>
</html>
1
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
上次更新: 2024-06-24 11:41:48