Project

General

Profile

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

haketilo / content / page_actions.js @ c12b9ee3

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
 * IMPORT report_content_type
15
 * IMPORTS_END
16
 */
17

    
18
let policy_received_callback;
19
/* Snapshot url and content type early; these can be changed by other code. */
20
let url;
21
let is_html;
22
let port;
23
let loaded = false;
24
let scripts_awaiting = [];
25
let nonce;
26

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

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

    
45
function document_loaded(event)
46
{
47
    loaded = true;
48

    
49
    for (let script_text of scripts_awaiting)
50
	add_script(script_text);
51

    
52
    scripts_awaiting = undefined;
53
}
54

    
55
function add_script(script_text)
56
{
57
    if (!is_html)
58
	return;
59

    
60
    let script = document.createElement("script");
61
    script.textContent = script_text;
62
    script.setAttribute("nonce", nonce);
63
    script._hachette_payload = true;
64
    document.body.appendChild(script);
65

    
66
    report_script(script_text);
67
}
68

    
69
function handle_page_actions(script_nonce, policy_received_cb) {
70
    policy_received_callback = policy_received_cb;
71
    url = document.URL;
72
    is_html = /html/.test(document.contentType);
73
    report_content_type(document.contentType);
74

    
75
    document.addEventListener("DOMContentLoaded", document_loaded);
76
    port = browser.runtime.connect({name : CONNECTION_TYPE.PAGE_ACTIONS});
77
    port.onMessage.addListener(handle_message);
78
    port.postMessage({url});
79

    
80
    nonce = script_nonce;
81
}
82

    
83
/*
84
 * EXPORTS_START
85
 * EXPORT handle_page_actions
86
 * EXPORTS_END
87
 */
(4-4/6)