Debian Codegraph @

src/js/contentscripts/utils.js

raw
1 /*
2 * This file is part of Privacy Badger <https://privacybadger.org/>
3 * Copyright (C) 2018 Electronic Frontier Foundation
4 *
5 * Privacy Badger is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 3 as
7 * published by the Free Software Foundation.
8 *
9 * Privacy Badger is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with Privacy Badger. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18 (function () {
19
20 // don't inject into non-HTML documents (such as XML documents)
21 // but do inject into XHTML documents
22 if (document instanceof HTMLDocument === false && (
23 document instanceof XMLDocument === false ||
24 document.createElement('div') instanceof HTMLDivElement === false
25 )) {
26 return;
27 }
28
29 /**
30 * Executes a script in the page's JavaScript context.
31 *
32 * @param {String} text The content of the script to insert.
33 */
34 window.injectScript = function (text) {
35 let parent = document.documentElement,
36 script = document.createElement('script');
37
38 script.text = text;
39 script.async = false;
40
41 parent.insertBefore(script, parent.firstChild);
42 parent.removeChild(script);
43 };
44
45 function getFrameUrl() {
46 let url = document.location.href,
47 parentFrame = (document != window.top) && window.parent;
48 while (parentFrame && url && !url.startsWith("http")) {
49 try {
50 url = parentFrame.document.location.href;
51 } catch (ex) {
52 // ignore 'Blocked a frame with origin "..."
53 // from accessing a cross-origin frame.' exceptions
54 }
55 parentFrame = (parentFrame != window.top) && parentFrame.parent;
56 }
57 return url;
58 }
59 window.FRAME_URL = getFrameUrl();
60
61 // END FUNCTION DEFINITIONS ///////////////////////////////////////////////////
62
63 document.addEventListener("pbSurrogateMessage", function (e) {
64 if (e.detail && e.detail.type == "widgetFromSurrogate") {
65 chrome.runtime.sendMessage({
66 type: "widgetFromSurrogate",
67 name: e.detail.name,
68 data: e.detail.widgetData,
69 frameUrl: window.FRAME_URL
70 });
71 }
72 });
73
74 }());