Grammalecte  Check-in [2d45cbf498]

Overview
Comment:[fx] minor coding style adjustments
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | fx | comunicate
Files: files | file ages | folders
SHA3-256: 2d45cbf4988dcd100439cf881371ea7ffcfeb2136ffa12f2c66102740db82ea4
User & Date: olr on 2018-11-11 11:47:12
Other Links: branch diff | manifest | tags
Context
2018-11-12
12:22
[fx] minor coding style adjustments check-in: 74f2ec49cc user: olr tags: fx, comunicate
2018-11-11
11:47
[fx] minor coding style adjustments check-in: 2d45cbf498 user: olr tags: fx, comunicate
2018-11-10
14:23
Fix some case check-in: 73aa037b8d user: IllusionPerdu tags: comunicate
Changes

Modified gc_lang/fr/webext/content_scripts/event.js from [d1ea962963] to [8bfc3ad28c].

39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
    var eventGrammalecte = new CustomEvent("GrammalecteEvent", { detail: JSON.stringify(dataToSend) });
    document.dispatchEvent(eventGrammalecte);
    return dataToSend.IdAction;
}

// ! Envoie de l'information que l'injection est bien faite ;)
// (peut être lu aussi bien par la page web que le content script)
var customAPILoaded = new CustomEvent("GrammalecteIsLoaded");
document.dispatchEvent(customAPILoaded);

// Gros Hack : Auto add a button in tinymce ;)

// Page to test v4 https://www.quackit.com/html/html_editors/tinymce_editor.cfm
// https://www.responsivefilemanager.com/demo.php








|







39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
    var eventGrammalecte = new CustomEvent("GrammalecteEvent", { detail: JSON.stringify(dataToSend) });
    document.dispatchEvent(eventGrammalecte);
    return dataToSend.IdAction;
}

// ! Envoie de l'information que l'injection est bien faite ;)
// (peut être lu aussi bien par la page web que le content script)
var customAPILoaded = new CustomEvent("GLInjectedScriptIsReady");
document.dispatchEvent(customAPILoaded);

// Gros Hack : Auto add a button in tinymce ;)

// Page to test v4 https://www.quackit.com/html/html_editors/tinymce_editor.cfm
// https://www.responsivefilemanager.com/demo.php

112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
            let iframeElement;
            if (typeof xEditorAdd.iframeElement !== "undefined" && typeof xEditorAdd.iframeElement.id !== "undefined") {
                iframeElement = xEditorAdd.iframeElement.id;
            } else if (typeof xEditorAdd.editorId !== "undefined") {
                iframeElement = xEditorAdd.editorId + "_ifr";
            }

            sendToGrammalecte({ spellcheck: sText, iframe: iframeElement });
        }
    });
}

function TinyInPage() {
    for (var i = tinyMCE.editors.length - 1; i > -1; i--) {
        let idTiny = tinyMCE.editors[i].id;







|







112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
            let iframeElement;
            if (typeof xEditorAdd.iframeElement !== "undefined" && typeof xEditorAdd.iframeElement.id !== "undefined") {
                iframeElement = xEditorAdd.iframeElement.id;
            } else if (typeof xEditorAdd.editorId !== "undefined") {
                iframeElement = xEditorAdd.editorId + "_ifr";
            }

            sendToGrammalecte({ sTextToParse: sText, iframe: iframeElement });
        }
    });
}

function TinyInPage() {
    for (var i = tinyMCE.editors.length - 1; i > -1; i--) {
        let idTiny = tinyMCE.editors[i].id;
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
    if (tinyMCE.majorVersion >= 4) {
        tinyMCE.on("AddEditor", TinyOnEditor);
    } else if (tinyMCE.majorVersion >= 3) {
        tinyMCE.onAddEditor.add(TinyOnEditor);
    }
    try {
        TinyInPage();
    } catch (error) {}


}

/* // ! In the webpage script :
document.addEventListener('GrammalecteIsLoaded', function() {
    // Le gestionnaire d'évènement est prêt!
    // La page web peut effectuer des actions
    ...
});
...
// Pour demander une correction sur le texte
sendToGrammalecte({"spellcheck": "salut comment ca vaa?"});
// Pour demander une correction sur un élément html
sendToGrammalecte({"spellcheck": true, "elm": elementHTML});
// Pour avoir le lexicographe sur un texte
sendToGrammalecte({"lexique": "salut comment ca vaa?"});
// Pour avoir le lexicographe sur un élément html
sendToGrammalecte({"lexique": true, "elm": elementHTML});
*/







|
>
>



|






|

|

|

|

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
    if (tinyMCE.majorVersion >= 4) {
        tinyMCE.on("AddEditor", TinyOnEditor);
    } else if (tinyMCE.majorVersion >= 3) {
        tinyMCE.onAddEditor.add(TinyOnEditor);
    }
    try {
        TinyInPage();
    } catch (e) {
        console.error(e);
    }
}

/* // ! In the webpage script :
document.addEventListener('GLInjectedScriptIsReady', function() {
    // Le gestionnaire d'évènement est prêt!
    // La page web peut effectuer des actions
    ...
});
...
// Pour demander une correction sur le texte
sendToGrammalecte({"sTextToParse": "salut comment ca vaa?"});
// Pour demander une correction sur un élément html
sendToGrammalecte({"sTextToParse": true, "elm": elementHTML});
// Pour avoir le lexicographe sur un texte
sendToGrammalecte({"sTextForLexicographer": "salut comment ca vaa?"});
// Pour avoir le lexicographe sur un élément html
sendToGrammalecte({"sTextForLexicographer": true, "elm": elementHTML});
*/

Modified gc_lang/fr/webext/content_scripts/init.js from [d32aff06fe] to [324ce24005].

9
10
11
12
13
14
15
16

17
18
19
20
21
22
23
    Not possible to load content from within the extension:
    https://bugzilla.mozilla.org/show_bug.cgi?id=1267027
    No SharedWorker, no images allowed for now…
*/

"use strict";

function showError(e) {

    console.error(e.fileName + "\n" + e.name + "\nline: " + e.lineNumber + "\n" + e.message);
}

// Chrome don’t follow the W3C specification:
// https://browserext.github.io/browserext/
let bChrome = false;
if (typeof browser !== "object") {







|
>







9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
    Not possible to load content from within the extension:
    https://bugzilla.mozilla.org/show_bug.cgi?id=1267027
    No SharedWorker, no images allowed for now…
*/

"use strict";

function showError (e) {
    // because console can’t display error objects from content script
    console.error(e.fileName + "\n" + e.name + "\nline: " + e.lineNumber + "\n" + e.message);
}

// Chrome don’t follow the W3C specification:
// https://browserext.github.io/browserext/
let bChrome = false;
if (typeof browser !== "object") {
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
    img.src = (URL || webkitURL).createObjectURL(blobTxt); // webkitURL is obsolete: https://bugs.webkit.org/show_bug.cgi?id=167518
    Array.filter(document.getElementsByClassName(sContainerClass), function (oElem) {
        oElem.appendChild(img);
    });
}
*/

var tinyAdd = {};

const oGrammalecte = {
    nMenu: 0,
    lMenu: [],

    oTFPanel: null,
    oLxgPanel: null,
    oGCPanel: null,

    oMessageBox: null,

    xRightClickedNode: null,

    xObserver: null,

    sExtensionUrl: null,

    listenRightClick: function() {
        // Node where a right click is done
        // Bug report: https://bugzilla.mozilla.org/show_bug.cgi?id=1325814
        document.addEventListener(
            "contextmenu",
            function(xEvent) {
                this.xRightClickedNode = xEvent.target;
            }.bind(this),
            true
        );
    },

    clearRightClickedNode: function() {
        this.xRightClickedNode = null;
    },

    createMenus: function() {
        if (bChrome) {
            browser.storage.local.get("ui_options", this._createMenus.bind(this));
            return;
        }
        browser.storage.local.get("ui_options").then(this._createMenus.bind(this), showError);
    },

    _createMenus: function(dOptions) {
        if (dOptions.hasOwnProperty("ui_options")) {
            dOptions = dOptions.ui_options;
            if (dOptions.textarea) {
                for (let xNode of document.getElementsByTagName("textarea")) {
                    if (xNode.style.display !== "none" && xNode.style.visibility !== "hidden" && xNode.getAttribute("spellcheck") !== "false") {
                        this.lMenu.push(new GrammalecteMenu(this.nMenu, xNode));
                        this.nMenu += 1;
                    }
                }
            }
            if (dOptions.editablenode) {
                for (let xNode of document.querySelectorAll("[contenteditable]")) {
                    this.lMenu.push(new GrammalecteMenu(this.nMenu, xNode));
                    this.nMenu += 1;
                }
            }
        }
    },

    observePage: function() {
        /*
            When a textarea is added via jascript we add the menu :)
        */
        function NodeTinyMCE(xNode) {
            let parentNode = xNode.parentNode; //mutation.target
            if (
                typeof xNode !== "undefined" &&
                typeof xNode.id !== "undefined" &&
                typeof tinyAdd[xNode.id] === "undefined" &&
                (parentNode.classList.contains("mce-edit-area") || parentNode.classList.contains("mceIframeContainer"))
            ) {
                //console.log(tinyAdd, xNode, parentNode, parentNode.classList);
                tinyAdd[xNode.id] = true;
                sendToWebpage({ tiny: xNode.id.replace("_ifr", "") });
            }
        }
        this.xObserver = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
                for (let i = 0; i < mutation.addedNodes.length; i++) {
                    let MutationNode = mutation.addedNodes[i];
                    let tagName = MutationNode.tagName;

                    if (tagName == "TEXTAREA") {
                        oGrammalecte.lMenu.push(new GrammalecteMenu(oGrammalecte.nMenu, MutationNode));
                        oGrammalecte.nMenu += 1;







|

















|




|






|



|







|



















|



|




|


|
|



|
|







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
    img.src = (URL || webkitURL).createObjectURL(blobTxt); // webkitURL is obsolete: https://bugs.webkit.org/show_bug.cgi?id=167518
    Array.filter(document.getElementsByClassName(sContainerClass), function (oElem) {
        oElem.appendChild(img);
    });
}
*/

let oTinyAdd = {};

const oGrammalecte = {
    nMenu: 0,
    lMenu: [],

    oTFPanel: null,
    oLxgPanel: null,
    oGCPanel: null,

    oMessageBox: null,

    xRightClickedNode: null,

    xObserver: null,

    sExtensionUrl: null,

    listenRightClick: function () {
        // Node where a right click is done
        // Bug report: https://bugzilla.mozilla.org/show_bug.cgi?id=1325814
        document.addEventListener(
            "contextmenu",
            function (xEvent) {
                this.xRightClickedNode = xEvent.target;
            }.bind(this),
            true
        );
    },

    clearRightClickedNode: function () {
        this.xRightClickedNode = null;
    },

    createMenus: function () {
        if (bChrome) {
            browser.storage.local.get("ui_options", this._createMenus.bind(this));
            return;
        }
        browser.storage.local.get("ui_options").then(this._createMenus.bind(this), showError);
    },

    _createMenus: function (dOptions) {
        if (dOptions.hasOwnProperty("ui_options")) {
            dOptions = dOptions.ui_options;
            if (dOptions.textarea) {
                for (let xNode of document.getElementsByTagName("textarea")) {
                    if (xNode.style.display !== "none" && xNode.style.visibility !== "hidden" && xNode.getAttribute("spellcheck") !== "false") {
                        this.lMenu.push(new GrammalecteMenu(this.nMenu, xNode));
                        this.nMenu += 1;
                    }
                }
            }
            if (dOptions.editablenode) {
                for (let xNode of document.querySelectorAll("[contenteditable]")) {
                    this.lMenu.push(new GrammalecteMenu(this.nMenu, xNode));
                    this.nMenu += 1;
                }
            }
        }
    },

    observePage: function () {
        /*
            When a textarea is added via jascript we add the menu :)
        */
        function NodeTinyMCE (xNode) {
            let parentNode = xNode.parentNode; //mutation.target
            if (
                typeof xNode !== "undefined" &&
                typeof xNode.id !== "undefined" &&
                typeof oTinyAdd[xNode.id] === "undefined" &&
                (parentNode.classList.contains("mce-edit-area") || parentNode.classList.contains("mceIframeContainer"))
            ) {
                //console.log(oTinyAdd, xNode, parentNode, parentNode.classList);
                oTinyAdd[xNode.id] = true;
                sendToWebpage({ tiny: xNode.id.replace("_ifr", "") });
            }
        }
        this.xObserver = new MutationObserver(function (mutations) {
            mutations.forEach(function (mutation) {
                for (let i = 0; i < mutation.addedNodes.length; i++) {
                    let MutationNode = mutation.addedNodes[i];
                    let tagName = MutationNode.tagName;

                    if (tagName == "TEXTAREA") {
                        oGrammalecte.lMenu.push(new GrammalecteMenu(oGrammalecte.nMenu, MutationNode));
                        oGrammalecte.nMenu += 1;
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
                },
                50,
                this
            );
        }
    },

    createLxgPanel: function() {
        if (this.oLxgPanel === null) {
            this.oLxgPanel = new GrammalecteLexicographer("grammalecte_lxg_panel", "Lexicographe", 500, 700);
            this.oLxgPanel.insertIntoPage();
        }
    },

    createGCPanel: function() {
        if (this.oGCPanel === null) {
            this.oGCPanel = new GrammalecteGrammarChecker("grammalecte_gc_panel", "Grammalecte", 500, 700);
            this.oGCPanel.insertIntoPage();
        }
    },

    createMessageBox: function() {
        if (this.oMessageBox === null) {
            this.oMessageBox = new GrammalecteMessageBox("grammalecte_message_box", "Grammalecte");
            this.oMessageBox.insertIntoPage();
        }
    },

    startGCPanel: function(xNode = null) {
        this.createGCPanel();
        this.oGCPanel.clear();
        this.oGCPanel.show();
        this.oGCPanel.start(xNode);
        this.oGCPanel.startWaitIcon();
    },

    startLxgPanel: function() {
        this.createLxgPanel();
        this.oLxgPanel.clear();
        this.oLxgPanel.show();
        this.oLxgPanel.startWaitIcon();
    },

    startFTPanel: function(xNode = null) {
        this.createTFPanel();
        this.oTFPanel.start(xNode);
        this.oTFPanel.show();
    },

    showMessage: function(sMessage) {
        this.createMessageBox();
        this.oMessageBox.show();
        this.oMessageBox.setMessage(sMessage);
    },

    getPageText: function() {
        let sPageText = document.body.innerText;
        let nPos = sPageText.indexOf("__grammalecte_panel__");
        if (nPos >= 0) {
            sPageText = sPageText.slice(0, nPos);
        }
        return sPageText;
    },

    createNode: function(sType, oAttr, oDataset = null) {
        try {
            let xNode = document.createElement(sType);
            Object.assign(xNode, oAttr);
            if (oDataset) {
                Object.assign(xNode.dataset, oDataset);
            }
            return xNode;
        } catch (e) {
            showError(e);
        }
    },

    createStyle: function(sLinkCss, sLinkId = null, xNodeToAppendTo = null) {
        try {
            let xNode = document.createElement("link");
            Object.assign(xNode, {
                rel: "stylesheet",
                type: "text/css",
                media: "all",
                href: this.sExtensionUrl + sLinkCss







|






|






|






|














|





|





|








|












|







193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
                },
                50,
                this
            );
        }
    },

    createLxgPanel: function () {
        if (this.oLxgPanel === null) {
            this.oLxgPanel = new GrammalecteLexicographer("grammalecte_lxg_panel", "Lexicographe", 500, 700);
            this.oLxgPanel.insertIntoPage();
        }
    },

    createGCPanel: function () {
        if (this.oGCPanel === null) {
            this.oGCPanel = new GrammalecteGrammarChecker("grammalecte_gc_panel", "Grammalecte", 500, 700);
            this.oGCPanel.insertIntoPage();
        }
    },

    createMessageBox: function () {
        if (this.oMessageBox === null) {
            this.oMessageBox = new GrammalecteMessageBox("grammalecte_message_box", "Grammalecte");
            this.oMessageBox.insertIntoPage();
        }
    },

    startGCPanel: function (xNode=null) {
        this.createGCPanel();
        this.oGCPanel.clear();
        this.oGCPanel.show();
        this.oGCPanel.start(xNode);
        this.oGCPanel.startWaitIcon();
    },

    startLxgPanel: function() {
        this.createLxgPanel();
        this.oLxgPanel.clear();
        this.oLxgPanel.show();
        this.oLxgPanel.startWaitIcon();
    },

    startFTPanel: function (xNode = null) {
        this.createTFPanel();
        this.oTFPanel.start(xNode);
        this.oTFPanel.show();
    },

    showMessage: function (sMessage) {
        this.createMessageBox();
        this.oMessageBox.show();
        this.oMessageBox.setMessage(sMessage);
    },

    getPageText: function () {
        let sPageText = document.body.innerText;
        let nPos = sPageText.indexOf("__grammalecte_panel__");
        if (nPos >= 0) {
            sPageText = sPageText.slice(0, nPos);
        }
        return sPageText;
    },

    createNode: function(sType, oAttr, oDataset=null) {
        try {
            let xNode = document.createElement(sType);
            Object.assign(xNode, oAttr);
            if (oDataset) {
                Object.assign(xNode.dataset, oDataset);
            }
            return xNode;
        } catch (e) {
            showError(e);
        }
    },

    createStyle: function (sLinkCss, sLinkId=null, xNodeToAppendTo=null) {
        try {
            let xNode = document.createElement("link");
            Object.assign(xNode, {
                rel: "stylesheet",
                type: "text/css",
                media: "all",
                href: this.sExtensionUrl + sLinkCss
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
};

/*
    Connexion to the background
*/
let xGrammalectePort = browser.runtime.connect({ name: "content-script port" });

xGrammalectePort.onMessage.addListener(function(oMessage) {
    let { sActionDone, result, dInfo, bEnd, bError } = oMessage;
    let sText = "";
    switch (sActionDone) {
        case "init":
            oGrammalecte.sExtensionUrl = oMessage.sUrl;
            // Start
            oGrammalecte.listenRightClick();







|







290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
};

/*
    Connexion to the background
*/
let xGrammalectePort = browser.runtime.connect({ name: "content-script port" });

xGrammalectePort.onMessage.addListener(function (oMessage) {
    let { sActionDone, result, dInfo, bEnd, bError } = oMessage;
    let sText = "";
    switch (sActionDone) {
        case "init":
            oGrammalecte.sExtensionUrl = oMessage.sUrl;
            // Start
            oGrammalecte.listenRightClick();
403
404
405
406
407
408
409

410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
            oGrammalecte.rescanPage();
            break;
        default:
            console.log("[Content script] Unknown command: " + sActionDone);
    }
});


/*
    Communicate webpage script <=> web-extension
    La méthode d'injection de ce script est importante !

    Pour que la page web puisse envoyer des infos au background
    Page web => Script injecté => Content script => Background
    Pour la réponse se sont les même étape en sens inverse.
*/
var scriptEvent = document.createElement("script");
scriptEvent.src = browser.extension.getURL("content_scripts/event.js");
document.documentElement.appendChild(scriptEvent);

var min = Math.ceil(0);
var max = Math.floor(9999999);
function uniqueID() {
    return Date.now().toString(36) + "-" + (Math.floor(Math.random() * (max - min)) + min).toString(36);
}

// ! Ecoute des messages venant du scipt injecté
document.addEventListener("GrammalecteEvent", function(event) {
    let actionFromPage = JSON.parse(event.detail);
    //console.log(event);
    let sText = false;
    let dInfo = {};
    let elmForGramma = null;

    if (actionFromPage.iframe) {
        elmForGramma = document.getElementById(actionFromPage.iframe).contentWindow.document.body;
    }
    if (actionFromPage.elm) {
        elmForGramma = document.getElementById(actionFromPage.elm);
        sText = elmForGramma.tagName == "TEXTAREA" ? elmForGramma.value : elmForGramma.innerText;
        dInfo = { sTextAreaId: elmForGramma.id };
    }
    if (actionFromPage.spellcheck) {
        oGrammalecte.startGCPanel(elmForGramma);
        xGrammalectePort.postMessage({
            sCommand: "parseAndSpellcheck",
            dParam: { sText: sText || actionFromPage.spellcheck, sCountry: "FR", bDebug: false, bContext: false },
            dInfo: dInfo
        });
    }
    if (actionFromPage.lexique) {
        oGrammalecte.startLxgPanel();
        xGrammalectePort.postMessage({
            sCommand: "getListOfTokens",
            dParam: { sText: sText || actionFromPage.lexique },
            dInfo: dInfo
        });
    }
});

let isLoaded = false;
let bufferMsg = [];

// ! Permet d'envoyer des messages vers le scipt injecté
// (peut aussi être lu par un script sur la page web)
function sendToWebpage(dataAction) {
    let dataToSend = dataAction;
    if (typeof dataToSend.IdAction === "undefined") {
        dataToSend.IdAction = uniqueID();
    }
    if (dataAction.elm) {
        if (!dataAction.elm.id) {
            dataAction.elm.id = uniqueID();
        }
        dataToSend.elm = dataAction.elm.id;
    }

    if (!isLoaded) {
        bufferMsg.push(dataToSend);
    } else {
        //console.log('sendToWebpage', dataToSend);
        var eventGrammalecte = new CustomEvent("GrammalecteToPage", { detail: JSON.stringify(dataToSend) });
        document.dispatchEvent(eventGrammalecte);
    }

    return dataToSend.IdAction;
}

// ! Les message ne peuvent être envoyer qu'après que le script est injecté
document.addEventListener("GrammalecteIsLoaded", function() {
    //console.log("GrammalecteIsLoaded EXT");
    isLoaded = true;
    if (bufferMsg.length > 0) {
        for (const dataToSend of bufferMsg) {
            var eventGrammalecte = new CustomEvent("GrammalecteToPage", { detail: JSON.stringify(dataToSend) });
            document.dispatchEvent(eventGrammalecte);
        }
    }
});

sendToWebpage({ init: browser.extension.getURL("") });







>

|
|



|

|
|
|

|
|
|
|


|
|
|



|

|
|

|
|
|
|

|
|


|



|



|





|
|

|

|
|
|
|

|
|
|

|


|
|

|
|



|


|
|
|
|
|
|
|






404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
            oGrammalecte.rescanPage();
            break;
        default:
            console.log("[Content script] Unknown command: " + sActionDone);
    }
});


/*
    Communicate webpage script <=> WebExtension
    La méthode dinjection de ce script est importante !

    Pour que la page web puisse envoyer des infos au background
    Page web => Script injecté => Content script => Background
    Pour la réponse, ce sont les mêmes étapes en sens inverse.
*/
let xScriptNode = document.createElement("script");
xScriptNode.src = browser.extension.getURL("content_scripts/event.js");
document.documentElement.appendChild(xScriptNode);

let nMin = Math.ceil(0);
let nMax = Math.floor(9999999);
function uniqueID () {
    return Date.now().toString(36) + "-" + (Math.floor(Math.random() * (nMax - nMin)) + nMin).toString(36);
}

// ! Écoute des messages venant du script injecté
document.addEventListener("GrammalecteEvent", function (event) {
    let oActionFromPage = JSON.parse(event.detail);
    //console.log(event);
    let sText = false;
    let dInfo = {};
    let xNodeToParse = null;

    if (oActionFromPage.iframe) {
        xNodeToParse = document.getElementById(oActionFromPage.iframe).contentWindow.document.body;
    }
    if (oActionFromPage.elm) {
        xNodeToParse = document.getElementById(oActionFromPage.elm);
        sText = xNodeToParse.tagName == "TEXTAREA" ? xNodeToParse.value : xNodeToParse.innerText;
        dInfo = { sTextAreaId: xNodeToParse.id };
    }
    if (oActionFromPage.sTextToParse) {
        oGrammalecte.startGCPanel(xNodeToParse);
        xGrammalectePort.postMessage({
            sCommand: "parseAndSpellcheck",
            dParam: { sText: sText || oActionFromPage.sTextToParse, sCountry: "FR", bDebug: false, bContext: false },
            dInfo: dInfo
        });
    }
    if (oActionFromPage.sTextForLexicographer) {
        oGrammalecte.startLxgPanel();
        xGrammalectePort.postMessage({
            sCommand: "getListOfTokens",
            dParam: { sText: sText || oActionFromPage.sTextForLexicographer },
            dInfo: dInfo
        });
    }
});

let bInjectedScriptReady = false;
let lBufferMsg = [];

// ! Permet denvoyer des messages vers le script injecté
// (peut aussi être lu par un script sur la page web)
function sendToWebpage (oDataAction) {
    let oDataToSend = oDataAction;
    if (typeof oDataToSend.IdAction === "undefined") {
        oDataToSend.IdAction = uniqueID();
    }
    if (oDataAction.elm) {
        if (!oDataAction.elm.id) {
            oDataAction.elm.id = uniqueID();
        }
        oDataToSend.elm = oDataAction.elm.id;
    }

    if (!bInjectedScriptReady) {
        lBufferMsg.push(oDataToSend);
    } else {
        //console.log('sendToWebpage', oDataToSend);
        let eventGrammalecte = new CustomEvent("GrammalecteToPage", { detail: JSON.stringify(oDataToSend) });
        document.dispatchEvent(eventGrammalecte);
    }

    return oDataToSend.IdAction;
}

// ! Les messages ne peuvent être envoyés quaprès l’injection du script
document.addEventListener("GLInjectedScriptIsReady", function () {
    //console.log("GLInjectedScriptIsReady EXT");
    bInjectedScriptReady = true;
    if (lBufferMsg.length > 0) {
        for (const oDataToSend of lBufferMsg) {
            let eventGrammalecte = new CustomEvent("GrammalecteToPage", { detail: JSON.stringify(oDataToSend) });
            document.dispatchEvent(eventGrammalecte);
        }
    }
});

sendToWebpage({ init: browser.extension.getURL("") });