Project

General

Profile

Download (1.72 KB) Statistics
| Branch: | Tag: | Revision:

haketilo / content / page_actions.js @ 53837634

1
/**
2
 * Hachette handling of page actions in content scripts
3
 *
4
 * Copyright (C) 2021 Wojtek Kosior
5
 * Redistribution terms are gathered in the `copyright' file.
6
 */
7

    
8
/*
9
 * IMPORTS_START
10
 * IMPORT CONNECTION_TYPE
11
 * IMPORT browser
12
 * IMPORT report_script
13
 * IMPORT report_settings
14
 * IMPORTS_END
15
 */
16

    
17
let policy_received_callback;
18
/* Snapshot url early because document.URL can be changed by other code. */
19
let url;
20
let port;
21
let loaded = false;
22
let scripts_awaiting = [];
23
let nonce;
24

    
25
function handle_message(message)
26
{
27
    const [action, data] = message;
28

    
29
    if (action === "inject") {
30
	for (let script_text of data) {
31
	    if (loaded)
32
		add_script(script_text);
33
	    else
34
		scripts_awaiting.push(script_text);
35
	}
36
    }
37
    if (action === "settings") {
38
	report_settings(data);
39
	policy_received_callback({url, allow: !!data[1] && data[1].allow});
40
    }
41
}
42

    
43
function document_loaded(event)
44
{
45
    loaded = true;
46

    
47
    for (let script_text of scripts_awaiting)
48
	add_script(script_text);
49

    
50
    scripts_awaiting = undefined;
51
}
52

    
53
function add_script(script_text)
54
{
55
    let script = document.createElement("script");
56
    script.textContent = script_text;
57
    script.setAttribute("nonce", nonce);
58
    script._hachette_payload = true;
59
    document.body.appendChild(script);
60

    
61
    report_script(script_text);
62
}
63

    
64
function handle_page_actions(script_nonce, policy_received_cb) {
65
    policy_received_callback = policy_received_cb;
66
    url = document.URL;
67

    
68
    document.addEventListener("DOMContentLoaded", document_loaded);
69
    port = browser.runtime.connect({name : CONNECTION_TYPE.PAGE_ACTIONS});
70
    port.onMessage.addListener(handle_message);
71
    port.postMessage({url});
72

    
73
    nonce = script_nonce;
74
}
75

    
76
/*
77
 * EXPORTS_START
78
 * EXPORT handle_page_actions
79
 * EXPORTS_END
80
 */
(4-4/6)