Project

General

Profile

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

haketilo / content / page_actions.js @ 2bd35bc4

1
/**
2
 * This file is part of Haketilo.
3
 *
4
 * Function: Handle page actions in a content script.
5
 *
6
 * Copyright (C) 2021 Wojtek Kosior
7
 * Redistribution terms are gathered in the `copyright' file.
8
 */
9

    
10
/*
11
 * IMPORTS_START
12
 * IMPORT CONNECTION_TYPE
13
 * IMPORT browser
14
 * IMPORT report_script
15
 * IMPORT report_settings
16
 * IMPORT report_document_type
17
 * IMPORTS_END
18
 */
19

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

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

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

    
47
function document_ready(event)
48
{
49
    loaded = true;
50

    
51
    for (let script_text of scripts_awaiting)
52
	add_script(script_text);
53

    
54
    scripts_awaiting = undefined;
55
}
56

    
57
function add_script(script_text)
58
{
59
    if (!is_html)
60
	return;
61

    
62
    let script = document.createElement("script");
63
    script.textContent = script_text;
64
    script.setAttribute("nonce", nonce);
65
    script.haketilo_payload = true;
66
    document.body.appendChild(script);
67

    
68
    report_script(script_text);
69
}
70

    
71
function handle_page_actions(script_nonce, policy_received_cb,
72
			     doc_ready_promise) {
73
    policy_received_callback = policy_received_cb;
74
    url = document.URL;
75
    is_html = document instanceof HTMLDocument;
76
    report_document_type(is_html);
77

    
78
    doc_ready_promise.then(document_ready);
79

    
80
    port = browser.runtime.connect({name : CONNECTION_TYPE.PAGE_ACTIONS});
81
    port.onMessage.addListener(handle_message);
82
    port.postMessage({url});
83

    
84
    nonce = script_nonce;
85
}
86

    
87
/*
88
 * EXPORTS_START
89
 * EXPORT handle_page_actions
90
 * EXPORTS_END
91
 */
(3-3/4)