summaryrefslogtreecommitdiffstats
path: root/toolkit/components/webextensions/ext-webNavigation.js
blob: 904f3a4a78b00b4e6dcdc705d0afcb439df94aa6 (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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
"use strict";

var {classes: Cc, interfaces: Ci, utils: Cu} = Components;

Cu.import("resource://gre/modules/XPCOMUtils.jsm");

XPCOMUtils.defineLazyModuleGetter(this, "ExtensionManagement",
                                  "resource://gre/modules/ExtensionManagement.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "MatchURLFilters",
                                  "resource://gre/modules/MatchPattern.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "WebNavigation",
                                  "resource://gre/modules/WebNavigation.jsm");

Cu.import("resource://gre/modules/ExtensionUtils.jsm");
var {
  SingletonEventManager,
  ignoreEvent,
} = ExtensionUtils;

const defaultTransitionTypes = {
  topFrame: "link",
  subFrame: "auto_subframe",
};

const frameTransitions = {
  anyFrame: {
    qualifiers: ["server_redirect", "client_redirect", "forward_back"],
  },
  topFrame: {
    types: ["reload", "form_submit"],
  },
};

const tabTransitions = {
  topFrame: {
    qualifiers: ["from_address_bar"],
    types: ["auto_bookmark", "typed", "keyword", "generated", "link"],
  },
  subFrame: {
    types: ["manual_subframe"],
  },
};

function isTopLevelFrame({frameId, parentFrameId}) {
  return frameId == 0 && parentFrameId == -1;
}

function fillTransitionProperties(eventName, src, dst) {
  if (eventName == "onCommitted" || eventName == "onHistoryStateUpdated") {
    let frameTransitionData = src.frameTransitionData || {};
    let tabTransitionData = src.tabTransitionData || {};

    let transitionType, transitionQualifiers = [];

    // Fill transition properties for any frame.
    for (let qualifier of frameTransitions.anyFrame.qualifiers) {
      if (frameTransitionData[qualifier]) {
        transitionQualifiers.push(qualifier);
      }
    }

    if (isTopLevelFrame(dst)) {
      for (let type of frameTransitions.topFrame.types) {
        if (frameTransitionData[type]) {
          transitionType = type;
        }
      }

      for (let qualifier of tabTransitions.topFrame.qualifiers) {
        if (tabTransitionData[qualifier]) {
          transitionQualifiers.push(qualifier);
        }
      }

      for (let type of tabTransitions.topFrame.types) {
        if (tabTransitionData[type]) {
          transitionType = type;
        }
      }

      // If transitionType is not defined, defaults it to "link".
      if (!transitionType) {
        transitionType = defaultTransitionTypes.topFrame;
      }
    } else {
      // If it is sub-frame, transitionType defaults it to "auto_subframe",
      // "manual_subframe" is set only in case of a recent user interaction.
      transitionType = tabTransitionData.link ?
        "manual_subframe" : defaultTransitionTypes.subFrame;
    }

    // Fill the transition properties in the webNavigation event object.
    dst.transitionType = transitionType;
    dst.transitionQualifiers = transitionQualifiers;
  }
}

// Similar to WebRequestEventManager but for WebNavigation.
function WebNavigationEventManager(context, eventName) {
  let name = `webNavigation.${eventName}`;
  let register = (callback, urlFilters) => {
    // Don't create a MatchURLFilters instance if the listener does not include any filter.
    let filters = urlFilters ?
          new MatchURLFilters(urlFilters.url) : null;

    let listener = data => {
      if (!data.browser) {
        return;
      }

      let data2 = {
        url: data.url,
        timeStamp: Date.now(),
        frameId: ExtensionManagement.getFrameId(data.windowId),
        parentFrameId: ExtensionManagement.getParentFrameId(data.parentWindowId, data.windowId),
      };

      if (eventName == "onErrorOccurred") {
        data2.error = data.error;
      }

      // Fills in tabId typically.
      extensions.emit("fill-browser-data", data.browser, data2);
      if (data2.tabId < 0) {
        return;
      }

      fillTransitionProperties(eventName, data, data2);

      context.runSafe(callback, data2);
    };

    WebNavigation[eventName].addListener(listener, filters);
    return () => {
      WebNavigation[eventName].removeListener(listener);
    };
  };

  return SingletonEventManager.call(this, context, name, register);
}

WebNavigationEventManager.prototype = Object.create(SingletonEventManager.prototype);

function convertGetFrameResult(tabId, data) {
  return {
    errorOccurred: data.errorOccurred,
    url: data.url,
    tabId,
    frameId: ExtensionManagement.getFrameId(data.windowId),
    parentFrameId: ExtensionManagement.getParentFrameId(data.parentWindowId, data.windowId),
  };
}

extensions.registerSchemaAPI("webNavigation", "addon_parent", context => {
  return {
    webNavigation: {
      onTabReplaced: ignoreEvent(context, "webNavigation.onTabReplaced"),
      onBeforeNavigate: new WebNavigationEventManager(context, "onBeforeNavigate").api(),
      onCommitted: new WebNavigationEventManager(context, "onCommitted").api(),
      onDOMContentLoaded: new WebNavigationEventManager(context, "onDOMContentLoaded").api(),
      onCompleted: new WebNavigationEventManager(context, "onCompleted").api(),
      onErrorOccurred: new WebNavigationEventManager(context, "onErrorOccurred").api(),
      onReferenceFragmentUpdated: new WebNavigationEventManager(context, "onReferenceFragmentUpdated").api(),
      onHistoryStateUpdated: new WebNavigationEventManager(context, "onHistoryStateUpdated").api(),
      onCreatedNavigationTarget: ignoreEvent(context, "webNavigation.onCreatedNavigationTarget"),
      getAllFrames(details) {
        let tab = TabManager.getTab(details.tabId, context);

        let {innerWindowID, messageManager} = tab.linkedBrowser;
        let recipient = {innerWindowID};

        return context.sendMessage(messageManager, "WebNavigation:GetAllFrames", {}, {recipient})
                      .then((results) => results.map(convertGetFrameResult.bind(null, details.tabId)));
      },
      getFrame(details) {
        let tab = TabManager.getTab(details.tabId, context);

        let recipient = {
          innerWindowID: tab.linkedBrowser.innerWindowID,
        };

        let mm = tab.linkedBrowser.messageManager;
        return context.sendMessage(mm, "WebNavigation:GetFrame", {options: details}, {recipient})
                      .then((result) => {
                        return result ?
                          convertGetFrameResult(details.tabId, result) :
                          Promise.reject({message: `No frame found with frameId: ${details.frameId}`});
                      });
      },
    },
  };
});