summaryrefslogtreecommitdiff
path: root/qutebrowser/javascript/stylesheet.js
blob: bbffb46f9e5ceb2f91718c1025b52bd036f76a66 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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
131
132
133
134
135
136
137
138
// Copyright 2017 Ulrik de Muelenaere <ulrikdem@gmail.com>
// Copyright 2017-2021 Florian Bruhin (The Compiler) <mail@qutebrowser.org>
//
// SPDX-License-Identifier: GPL-3.0-or-later

"use strict";

window._qutebrowser.stylesheet = (function() {
    if (window._qutebrowser.stylesheet) {
        return window._qutebrowser.stylesheet;
    }

    const funcs = {};

    const xhtml_ns = "http://www.w3.org/1999/xhtml";
    const svg_ns = "http://www.w3.org/2000/svg";

    let root_elem;
    let style_elem;
    let css_content = "";

    let root_observer;
    let initialized = false;

    // Watch for rewrites of the root element and changes to its children,
    // then move the stylesheet to the end. Partially inspired by Stylus:
    // https://github.com/openstyles/stylus/blob/1.1.4.2/content/apply.js#L235-L355
    function watch_root() {
        if (!document.documentElement) {
            root_observer.observe(document, {"childList": true});
            return;
        }

        if (root_elem !== document.documentElement) {
            root_elem = document.documentElement;
            root_observer.disconnect();
            root_observer.observe(document, {"childList": true});
            root_observer.observe(root_elem, {"childList": true});
        }
        if (style_elem !== root_elem.lastChild) {
            root_elem.appendChild(style_elem);
        }
    }

    function create_style() {
        let ns = xhtml_ns;
        if (document.documentElement &&
            document.documentElement.namespaceURI === svg_ns) {
            ns = svg_ns;
        }
        style_elem = document.createElementNS(ns, "style");
        style_elem.textContent = css_content;
        root_observer = new MutationObserver(watch_root);
        watch_root();
    }

    // We should only inject the stylesheet if the document already has style
    // information associated with it. Otherwise we wait until the browser
    // rewrites it to an XHTML document showing the document tree. As a
    // starting point for exploring the relevant code in Chromium, see
    // https://github.com/qt/qtwebengine-chromium/blob/cfe8c60/chromium/third_party/WebKit/Source/core/xml/parser/XMLDocumentParser.cpp#L1539-L1540
    function check_style(node) {
        const stylesheet = node.nodeType === Node.PROCESSING_INSTRUCTION_NODE &&
                           node.target === "xml-stylesheet" &&
                           node.parentNode === document;
        const known_ns = node.nodeType === Node.ELEMENT_NODE &&
                         (node.namespaceURI === xhtml_ns ||
                          node.namespaceURI === svg_ns);
        return stylesheet || known_ns;
    }

    function init() {
        initialized = true;
        // Chromium will not rewrite a document inside a frame, so add the
        // stylesheet even if the document is unstyled.
        if (window !== window.top) {
            create_style();
            return;
        }

        const iter = document.createNodeIterator(document,
            NodeFilter.SHOW_PROCESSING_INSTRUCTION | NodeFilter.SHOW_ELEMENT);
        let node;
        while ((node = iter.nextNode())) {
            if (check_style(node)) {
                create_style();
                return;
            }
        }

        const style_observer = new MutationObserver((mutations) => {
            for (const mutation of mutations) {
                const nodes = mutation.addedNodes;
                for (let i = 0; i < nodes.length; ++i) {
                    if (check_style(nodes[i])) {
                        create_style();
                        style_observer.disconnect();
                        return;
                    }
                }
            }
        });
        style_observer.observe(document, {"childList": true, "subtree": true});
    }

    funcs.set_css = function(css) {
        if (!initialized) {
            init();
        }
        if (style_elem) {
            style_elem.textContent = css;
            // The browser seems to rewrite the document in same-origin frames
            // without notifying the mutation observer. Ensure that the
            // stylesheet is in the current document.
            watch_root();
        } else {
            css_content = css;
        }
        // Propagate the new CSS to all child frames.
        for (let i = 0; i < window.frames.length; ++i) {
            const frame = window.frames[i];
            try {
                if (frame._qutebrowser && frame._qutebrowser.stylesheet) {
                    frame._qutebrowser.stylesheet.set_css(css);
                }
            } catch (exc) {
                if (exc instanceof DOMException && exc.name === "SecurityError") {
                    // FIXME:qtwebengine This does not work for cross-origin frames.
                    console.log(`Failed to style frame: ${exc.message}`);
                } else {
                    throw exc;
                }
            }
        }
    };

    return funcs;
})();