summaryrefslogtreecommitdiff
path: root/src/bg/ContentScriptOnce.js
blob: 5be602eb55b244fbef53c132847da091d63f1826 (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
var ContentScriptOnce = (() => {
  "use strict";
  
  let requestMap = new Map();
  
  {
    let cleanup = r => {
      let {requestId} = r;
      let scripts = requestMap.get(requestId);
      if (scripts) {
        window.setTimeout(() => {
          requestMap.delete(requestId);
          for (let s of scripts) s.unregister();
        }, 0);
      }
    }
    
    let filter = {
      urls: ["<all_urls>"],
      types:  ["main_frame", "sub_frame", "object"]
    };
    let wr = browser.webRequest;
    for (let event of ["onCompleted", "onErrorOccurred"]) {
      wr[event].addListener(cleanup, filter);
    }
  }
  
  return {
    async execute(request, options) {
      let {requestId, url} = request; 
      let scripts = requestMap.get(requestId);
      if (!scripts) requestMap.set(requestId, scripts = new Set());
      try {
        let urlObj = new URL(url);
        if (urlObj.port) {
          urlObj.port = "";
          url = urlObj.toString();
        }
      } catch (e) {}
      let defOpts = {
        runAt: "document_start",
        matchAboutBlank: true,
        matches: [url],
        allFrames: true,
      };
      
      scripts.add(await browser.contentScripts.register(
        Object.assign(defOpts, options)
      ));
    }
  }
})();