Project

General

Profile

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

haketilo / content / page_actions.js @ 96068ada

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_document_type
16
 * IMPORTS_END
17
 */
18

    
19
let policy;
20
/* Snapshot url and content type early; these can be changed by other code. */
21
let url;
22
let is_html;
23
let port;
24
let loaded = false;
25
let scripts_awaiting = [];
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
    else {
40
	console.error(`Bad page action '${action}'.`);
41
    }
42
}
43

    
44
function document_ready(event)
45
{
46
    loaded = true;
47

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

    
51
    scripts_awaiting = undefined;
52
}
53

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

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

    
65
    report_script(script_text);
66
}
67

    
68
function handle_page_actions(_policy, doc_ready_promise) {
69
    policy = _policy;
70

    
71
    url = document.URL;
72
    is_html = document instanceof HTMLDocument;
73
    report_document_type(is_html);
74

    
75
    doc_ready_promise.then(document_ready);
76

    
77
    if (policy.payload) {
78
	port = browser.runtime.connect({name : CONNECTION_TYPE.PAGE_ACTIONS});
79
	port.onMessage.addListener(handle_message);
80
	port.postMessage({payload: policy.payload});
81
    }
82
}
83

    
84
/*
85
 * EXPORTS_START
86
 * EXPORT handle_page_actions
87
 * EXPORTS_END
88
 */
(3-3/4)