aboutsummaryrefslogtreecommitdiff
path: root/ext/fg/js/frame-ancestry-handler.js
blob: d51467f8ea3f64b9357a7c67f4a48769fb45c748 (plain)
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
/*
 * Copyright (C) 2021  Yomichan Authors
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

/* global
 * api
 */

/**
 * This class is used to return the ancestor frame IDs for the current frame.
 * This is a workaround to using the `webNavigation.getAllFrames` API, which
 * would require an additional permission that is otherwise unnecessary.
 */
class FrameAncestryHandler {
    /**
     * Creates a new instance.
     * @param frameId The frame ID of the current frame the instance is instantiated in.
     */
    constructor(frameId) {
        this._frameId = frameId;
        this._isPrepared = false;
        this._requestMessageId = 'FrameAncestryHandler.requestFrameInfo';
        this._responseMessageId = `${this._requestMessageId}.response`;
    }

    /**
     * Gets the frame ID that the instance is instantiated in.
     */
    get frameId() {
        return this._frameId;
    }

    /**
     * Initializes event event listening.
     */
    prepare() {
        if (this._isPrepared) { return; }
        window.addEventListener('message', this._onWindowMessage.bind(this), false);
        this._isPrepared = true;
    }

    /**
     * Gets the frame ancestry information for the current frame. If the frame is the
     * root frame, an empty array is returned. Otherwise, an array of frame IDs is returned,
     * starting from the nearest ancestor.
     * @param timeout The maximum time to wait to receive a response to frame information requests.
     * @returns An array of frame IDs corresponding to the ancestors of the current frame.
     */
    getFrameAncestryInfo(timeout=5000) {
        return new Promise((resolve, reject) => {
            const targetWindow = window.parent;
            if (window === targetWindow) {
                resolve([]);
                return;
            }

            const uniqueId = generateId(16);
            const responseMessageId = this._responseMessageId;
            const results = [];
            let resultsExpectedCount = null;
            let resultsCount = 0;
            let timer = null;

            const cleanup = () => {
                if (timer !== null) {
                    clearTimeout(timer);
                    timer = null;
                }
                chrome.runtime.onMessage.removeListener(onMessage);
            };
            const onMessage = (message, sender, sendResponse) => {
                // Validate message
                if (
                    typeof message !== 'object' ||
                    message === null ||
                    message.action !== responseMessageId
                ) {
                    return;
                }

                const {params} = message;
                if (params.uniqueId !== uniqueId) { return; } // Wrong ID

                const {frameId, index, more} = params;
                console.log({frameId, index, more});
                if (typeof results[index] !== 'undefined') { return; } // Invalid repeat

                // Add result
                results[index] = frameId;
                ++resultsCount;
                if (!more) {
                    resultsExpectedCount = index + 1;
                }

                if (resultsExpectedCount !== null && resultsCount >= resultsExpectedCount) {
                    // Cleanup
                    cleanup();
                    sendResponse();

                    // Finish
                    resolve(results);
                } else {
                    resetTimeout();
                }
            };
            const onTimeout = () => {
                timer = null;
                cleanup();
                reject(new Error(`Request for parent frame ID timed out after ${timeout}ms`));
            };
            const resetTimeout = () => {
                if (timer !== null) { clearTimeout(timer); }
                timer = setTimeout(onTimeout, timeout);
            };

            // Start
            chrome.runtime.onMessage.addListener(onMessage);
            resetTimeout();
            this._requestFrameInfo(targetWindow, uniqueId, this._frameId, 0);
        });
    }

    // Private

    _onWindowMessage(event) {
        const {data} = event;
        if (
            typeof data === 'object' &&
            data !== null &&
            data.action === this._requestMessageId
        ) {
            try {
                this._onRequestFrameInfo(data.params);
            } catch (e) {
                // NOP
            }
        }
    }

    _onRequestFrameInfo({uniqueId, originFrameId, index}) {
        if (
            typeof uniqueId !== 'string' ||
            typeof originFrameId !== 'number' ||
            !this._isNonNegativeInteger(index)
        ) {
            return;
        }

        const {parent} = window;
        const more = (window !== parent);

        const responseParams = {uniqueId, frameId: this._frameId, index, more};
        this._safeSendMessageToFrame(originFrameId, this._responseMessageId, responseParams);

        if (more) {
            this._requestFrameInfo(parent, uniqueId, originFrameId, index + 1);
        }
    }

    async _safeSendMessageToFrame(frameId, action, params) {
        try {
            await api.sendMessageToFrame(frameId, action, params);
        } catch (e) {
            // NOP
        }
    }

    _requestFrameInfo(targetWindow, uniqueId, originFrameId, index) {
        targetWindow.postMessage({
            action: this._requestMessageId,
            params: {uniqueId, originFrameId, index}
        }, '*');
    }

    _isNonNegativeInteger(value) {
        return (
            typeof value === 'number' &&
            Number.isFinite(value) &&
            value >= 0 &&
            Math.floor(value) === value
        );
    }
}