/
browser.js
executable file
·8434 lines (7301 loc) · 290 KB
/
browser.js
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*-
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
var Ci = Components.interfaces;
var Cu = Components.utils;
var Cc = Components.classes;
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://gre/modules/ContextualIdentityService.jsm");
Cu.import("resource://gre/modules/NotificationDB.jsm");
// lazy module getters
[
["AboutHome", "resource:///modules/AboutHome.jsm"],
["AddonWatcher", "resource://gre/modules/AddonWatcher.jsm"],
["AppConstants", "resource://gre/modules/AppConstants.jsm"],
["BrowserUITelemetry", "resource:///modules/BrowserUITelemetry.jsm"],
["BrowserUsageTelemetry", "resource:///modules/BrowserUsageTelemetry.jsm"],
["BrowserUtils", "resource://gre/modules/BrowserUtils.jsm"],
["CastingApps", "resource:///modules/CastingApps.jsm"],
["CharsetMenu", "resource://gre/modules/CharsetMenu.jsm"],
["Color", "resource://gre/modules/Color.jsm"],
["ContentSearch", "resource:///modules/ContentSearch.jsm"],
["Deprecated", "resource://gre/modules/Deprecated.jsm"],
["E10SUtils", "resource:///modules/E10SUtils.jsm"],
["FormValidationHandler", "resource:///modules/FormValidationHandler.jsm"],
["GMPInstallManager", "resource://gre/modules/GMPInstallManager.jsm"],
["LightweightThemeManager", "resource://gre/modules/LightweightThemeManager.jsm"],
["Log", "resource://gre/modules/Log.jsm"],
["LoginManagerParent", "resource://gre/modules/LoginManagerParent.jsm"],
["NewTabUtils", "resource://gre/modules/NewTabUtils.jsm"],
["PageThumbs", "resource://gre/modules/PageThumbs.jsm"],
["PluralForm", "resource://gre/modules/PluralForm.jsm"],
["Preferences", "resource://gre/modules/Preferences.jsm"],
["PrivateBrowsingUtils", "resource://gre/modules/PrivateBrowsingUtils.jsm"],
["ProcessHangMonitor", "resource:///modules/ProcessHangMonitor.jsm"],
["PromiseUtils", "resource://gre/modules/PromiseUtils.jsm"],
["ReaderMode", "resource://gre/modules/ReaderMode.jsm"],
["ReaderParent", "resource:///modules/ReaderParent.jsm"],
["RecentWindow", "resource:///modules/RecentWindow.jsm"],
["SessionStore", "resource:///modules/sessionstore/SessionStore.jsm"],
["ShortcutUtils", "resource://gre/modules/ShortcutUtils.jsm"],
["SimpleServiceDiscovery", "resource://gre/modules/SimpleServiceDiscovery.jsm"],
["SitePermissions", "resource:///modules/SitePermissions.jsm"],
["Social", "resource:///modules/Social.jsm"],
["TabCrashHandler", "resource:///modules/ContentCrashHandlers.jsm"],
["Task", "resource://gre/modules/Task.jsm"],
["TelemetryStopwatch", "resource://gre/modules/TelemetryStopwatch.jsm"],
["Translation", "resource:///modules/translation/Translation.jsm"],
["UITour", "resource:///modules/UITour.jsm"],
["UpdateUtils", "resource://gre/modules/UpdateUtils.jsm"],
["Weave", "resource://services-sync/main.js"],
["fxAccounts", "resource://gre/modules/FxAccounts.jsm"],
["gDevTools", "resource://devtools/client/framework/gDevTools.jsm"],
["gDevToolsBrowser", "resource://devtools/client/framework/gDevTools.jsm"],
["webrtcUI", "resource:///modules/webrtcUI.jsm", ]
].forEach(([name, resource]) => XPCOMUtils.defineLazyModuleGetter(this, name, resource));
XPCOMUtils.defineLazyModuleGetter(this, "SafeBrowsing",
"resource://gre/modules/SafeBrowsing.jsm");
if (AppConstants.MOZ_CRASHREPORTER) {
XPCOMUtils.defineLazyModuleGetter(this, "PluginCrashReporter",
"resource:///modules/ContentCrashHandlers.jsm");
}
// lazy service getters
[
["Favicons", "@mozilla.org/browser/favicon-service;1", "mozIAsyncFavicons"],
["WindowsUIUtils", "@mozilla.org/windows-ui-utils;1", "nsIWindowsUIUtils"],
["gAboutNewTabService", "@mozilla.org/browser/aboutnewtab-service;1", "nsIAboutNewTabService"],
["gDNSService", "@mozilla.org/network/dns-service;1", "nsIDNSService"],
].forEach(([name, cc, ci]) => XPCOMUtils.defineLazyServiceGetter(this, name, cc, ci));
if (AppConstants.MOZ_CRASHREPORTER) {
XPCOMUtils.defineLazyServiceGetter(this, "gCrashReporter",
"@mozilla.org/xre/app-info;1",
"nsICrashReporter");
}
XPCOMUtils.defineLazyGetter(this, "BrowserToolboxProcess", function() {
let tmp = {};
Cu.import("resource://devtools/client/framework/ToolboxProcess.jsm", tmp);
return tmp.BrowserToolboxProcess;
});
XPCOMUtils.defineLazyGetter(this, "gBrowserBundle", function() {
return Services.strings.createBundle('chrome://browser/locale/browser.properties');
});
XPCOMUtils.defineLazyGetter(this, "gCustomizeMode", function() {
let scope = {};
Cu.import("resource:///modules/CustomizeMode.jsm", scope);
return new scope.CustomizeMode(window);
});
XPCOMUtils.defineLazyGetter(window, "gShowPageResizers", function () {
// Only show resizers on Windows 2000 and XP
return AppConstants.isPlatformAndVersionAtMost("win", "5.9");
});
XPCOMUtils.defineLazyGetter(this, "gPrefService", function() {
return Services.prefs;
});
XPCOMUtils.defineLazyGetter(this, "InlineSpellCheckerUI", function() {
let tmp = {};
Cu.import("resource://gre/modules/InlineSpellChecker.jsm", tmp);
return new tmp.InlineSpellChecker();
});
XPCOMUtils.defineLazyGetter(this, "PageMenuParent", function() {
let tmp = {};
Cu.import("resource://gre/modules/PageMenu.jsm", tmp);
return new tmp.PageMenuParent();
});
XPCOMUtils.defineLazyGetter(this, "PopupNotifications", function () {
let tmp = {};
Cu.import("resource://gre/modules/PopupNotifications.jsm", tmp);
try {
return new tmp.PopupNotifications(gBrowser,
document.getElementById("notification-popup"),
document.getElementById("notification-popup-box"));
} catch (ex) {
Cu.reportError(ex);
return null;
}
});
XPCOMUtils.defineLazyGetter(this, "Win7Features", function () {
if (AppConstants.platform != "win")
return null;
const WINTASKBAR_CONTRACTID = "@mozilla.org/windows-taskbar;1";
if (WINTASKBAR_CONTRACTID in Cc &&
Cc[WINTASKBAR_CONTRACTID].getService(Ci.nsIWinTaskbar).available) {
let AeroPeek = Cu.import("resource:///modules/WindowsPreviewPerTab.jsm", {}).AeroPeek;
return {
onOpenWindow: function () {
AeroPeek.onOpenWindow(window);
},
onCloseWindow: function () {
AeroPeek.onCloseWindow(window);
}
};
}
return null;
});
const nsIWebNavigation = Ci.nsIWebNavigation;
var gLastBrowserCharset = null;
var gLastValidURLStr = "";
var gInPrintPreviewMode = false;
var gContextMenu = null; // nsContextMenu instance
var gMultiProcessBrowser =
window.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIWebNavigation)
.QueryInterface(Ci.nsILoadContext)
.useRemoteTabs;
var gAppInfo = Cc["@mozilla.org/xre/app-info;1"]
.getService(Ci.nsIXULAppInfo)
.QueryInterface(Ci.nsIXULRuntime);
if (AppConstants.platform != "macosx") {
var gEditUIVisible = true;
}
/* globals gBrowser, gNavToolbox, gURLBar, gNavigatorBundle*/
[
["gBrowser", "content"],
["gNavToolbox", "navigator-toolbox"],
["gURLBar", "urlbar"],
["gNavigatorBundle", "bundle_browser"]
].forEach(function (elementGlobal) {
var [name, id] = elementGlobal;
window.__defineGetter__(name, function () {
var element = document.getElementById(id);
if (!element)
return null;
delete window[name];
return window[name] = element;
});
window.__defineSetter__(name, function (val) {
delete window[name];
return window[name] = val;
});
});
// Smart getter for the findbar. If you don't wish to force the creation of
// the findbar, check gFindBarInitialized first.
this.__defineGetter__("gFindBar", function() {
return window.gBrowser.getFindBar();
});
this.__defineGetter__("gFindBarInitialized", function() {
return window.gBrowser.isFindBarInitialized();
});
this.__defineGetter__("AddonManager", function() {
let tmp = {};
Cu.import("resource://gre/modules/AddonManager.jsm", tmp);
return this.AddonManager = tmp.AddonManager;
});
this.__defineSetter__("AddonManager", function (val) {
delete this.AddonManager;
return this.AddonManager = val;
});
var gInitialPages = [
"about:tor",
#ifdef TOR_BROWSER_UPDATE
"about:tbupdate",
#endif
"about:blank",
"about:newtab",
"about:home",
"about:privatebrowsing",
"about:welcomeback",
"about:sessionrestore"
];
function* browserWindows() {
let windows = Services.wm.getEnumerator("navigator:browser");
while (windows.hasMoreElements())
yield windows.getNext();
}
/**
* We can avoid adding multiple load event listeners and save some time by adding
* one listener that calls all real handlers.
*/
function pageShowEventHandlers(persisted) {
XULBrowserWindow.asyncUpdateUI();
}
function UpdateBackForwardCommands(aWebNavigation) {
var backBroadcaster = document.getElementById("Browser:Back");
var forwardBroadcaster = document.getElementById("Browser:Forward");
// Avoid setting attributes on broadcasters if the value hasn't changed!
// Remember, guys, setting attributes on elements is expensive! They
// get inherited into anonymous content, broadcast to other widgets, etc.!
// Don't do it if the value hasn't changed! - dwh
var backDisabled = backBroadcaster.hasAttribute("disabled");
var forwardDisabled = forwardBroadcaster.hasAttribute("disabled");
if (backDisabled == aWebNavigation.canGoBack) {
if (backDisabled)
backBroadcaster.removeAttribute("disabled");
else
backBroadcaster.setAttribute("disabled", true);
}
if (forwardDisabled == aWebNavigation.canGoForward) {
if (forwardDisabled)
forwardBroadcaster.removeAttribute("disabled");
else
forwardBroadcaster.setAttribute("disabled", true);
}
}
/**
* Click-and-Hold implementation for the Back and Forward buttons
* XXXmano: should this live in toolbarbutton.xml?
*/
function SetClickAndHoldHandlers() {
// Bug 414797: Clone the back/forward buttons' context menu into both buttons.
let popup = document.getElementById("backForwardMenu").cloneNode(true);
popup.removeAttribute("id");
// Prevent the back/forward buttons' context attributes from being inherited.
popup.setAttribute("context", "");
let backButton = document.getElementById("back-button");
backButton.setAttribute("type", "menu");
backButton.appendChild(popup);
gClickAndHoldListenersOnElement.add(backButton);
let forwardButton = document.getElementById("forward-button");
popup = popup.cloneNode(true);
forwardButton.setAttribute("type", "menu");
forwardButton.appendChild(popup);
gClickAndHoldListenersOnElement.add(forwardButton);
}
const gClickAndHoldListenersOnElement = {
_timers: new Map(),
_mousedownHandler(aEvent) {
if (aEvent.button != 0 ||
aEvent.currentTarget.open ||
aEvent.currentTarget.disabled)
return;
// Prevent the menupopup from opening immediately
aEvent.currentTarget.firstChild.hidden = true;
aEvent.currentTarget.addEventListener("mouseout", this, false);
aEvent.currentTarget.addEventListener("mouseup", this, false);
this._timers.set(aEvent.currentTarget, setTimeout((b) => this._openMenu(b), 500, aEvent.currentTarget));
},
_clickHandler(aEvent) {
if (aEvent.button == 0 &&
aEvent.target == aEvent.currentTarget &&
!aEvent.currentTarget.open &&
!aEvent.currentTarget.disabled) {
let cmdEvent = document.createEvent("xulcommandevent");
cmdEvent.initCommandEvent("command", true, true, window, 0,
aEvent.ctrlKey, aEvent.altKey, aEvent.shiftKey,
aEvent.metaKey, null);
aEvent.currentTarget.dispatchEvent(cmdEvent);
// This is here to cancel the XUL default event
// dom.click() triggers a command even if there is a click handler
// however this can now be prevented with preventDefault().
aEvent.preventDefault();
}
},
_openMenu(aButton) {
this._cancelHold(aButton);
aButton.firstChild.hidden = false;
aButton.open = true;
},
_mouseoutHandler(aEvent) {
let buttonRect = aEvent.currentTarget.getBoundingClientRect();
if (aEvent.clientX >= buttonRect.left &&
aEvent.clientX <= buttonRect.right &&
aEvent.clientY >= buttonRect.bottom)
this._openMenu(aEvent.currentTarget);
else
this._cancelHold(aEvent.currentTarget);
},
_mouseupHandler(aEvent) {
this._cancelHold(aEvent.currentTarget);
},
_cancelHold(aButton) {
clearTimeout(this._timers.get(aButton));
aButton.removeEventListener("mouseout", this, false);
aButton.removeEventListener("mouseup", this, false);
},
handleEvent(e) {
switch (e.type) {
case "mouseout":
this._mouseoutHandler(e);
break;
case "mousedown":
this._mousedownHandler(e);
break;
case "click":
this._clickHandler(e);
break;
case "mouseup":
this._mouseupHandler(e);
break;
}
},
remove(aButton) {
aButton.removeEventListener("mousedown", this, true);
aButton.removeEventListener("click", this, true);
},
add(aElm) {
this._timers.delete(aElm);
aElm.addEventListener("mousedown", this, true);
aElm.addEventListener("click", this, true);
}
};
const gSessionHistoryObserver = {
observe: function(subject, topic, data)
{
if (topic != "browser:purge-session-history")
return;
var backCommand = document.getElementById("Browser:Back");
backCommand.setAttribute("disabled", "true");
var fwdCommand = document.getElementById("Browser:Forward");
fwdCommand.setAttribute("disabled", "true");
// Hide session restore button on about:home
window.messageManager.broadcastAsyncMessage("Browser:HideSessionRestoreButton");
// Clear undo history of the URL bar
gURLBar.editor.transactionManager.clear()
}
};
/**
* Given a starting docshell and a URI to look up, find the docshell the URI
* is loaded in.
* @param aDocument
* A document to find instead of using just a URI - this is more specific.
* @param aDocShell
* The doc shell to start at
* @param aSoughtURI
* The URI that we're looking for
* @returns The doc shell that the sought URI is loaded in. Can be in
* subframes.
*/
function findChildShell(aDocument, aDocShell, aSoughtURI) {
aDocShell.QueryInterface(Components.interfaces.nsIWebNavigation);
aDocShell.QueryInterface(Components.interfaces.nsIInterfaceRequestor);
var doc = aDocShell.getInterface(Components.interfaces.nsIDOMDocument);
if ((aDocument && doc == aDocument) ||
(aSoughtURI && aSoughtURI.spec == aDocShell.currentURI.spec))
return aDocShell;
var node = aDocShell.QueryInterface(Components.interfaces.nsIDocShellTreeItem);
for (var i = 0; i < node.childCount; ++i) {
var docShell = node.getChildAt(i);
docShell = findChildShell(aDocument, docShell, aSoughtURI);
if (docShell)
return docShell;
}
return null;
}
var gPopupBlockerObserver = {
_reportButton: null,
onReportButtonMousedown: function (aEvent)
{
// If this method is called on the same event tick as the popup gets
// hidden, do nothing to avoid re-opening the popup.
if (aEvent.button != 0 || aEvent.target != this._reportButton || this.isPopupHidingTick)
return;
document.getElementById("blockedPopupOptions")
.openPopup(this._reportButton, "after_end", 0, 2, false, false, aEvent);
},
handleEvent: function (aEvent)
{
if (aEvent.originalTarget != gBrowser.selectedBrowser)
return;
if (!this._reportButton)
this._reportButton = document.getElementById("page-report-button");
if (!gBrowser.selectedBrowser.blockedPopups ||
!gBrowser.selectedBrowser.blockedPopups.length) {
// Hide the icon in the location bar (if the location bar exists)
this._reportButton.hidden = true;
// Hide the notification box (if it's visible).
let notificationBox = gBrowser.getNotificationBox();
let notification = notificationBox.getNotificationWithValue("popup-blocked");
if (notification) {
notificationBox.removeNotification(notification, false);
}
return;
}
this._reportButton.hidden = false;
// Only show the notification again if we've not already shown it. Since
// notifications are per-browser, we don't need to worry about re-adding
// it.
if (!gBrowser.selectedBrowser.blockedPopups.reported) {
if (gPrefService.getBoolPref("privacy.popups.showBrowserMessage")) {
var brandBundle = document.getElementById("bundle_brand");
var brandShortName = brandBundle.getString("brandShortName");
var popupCount = gBrowser.selectedBrowser.blockedPopups.length;
var stringKey = AppConstants.platform == "win"
? "popupWarningButton"
: "popupWarningButtonUnix";
var popupButtonText = gNavigatorBundle.getString(stringKey);
var popupButtonAccesskey = gNavigatorBundle.getString(stringKey + ".accesskey");
var messageBase = gNavigatorBundle.getString("popupWarning.message");
var message = PluralForm.get(popupCount, messageBase)
.replace("#1", brandShortName)
.replace("#2", popupCount);
let notificationBox = gBrowser.getNotificationBox();
let notification = notificationBox.getNotificationWithValue("popup-blocked");
if (notification) {
notification.label = message;
}
else {
var buttons = [{
label: popupButtonText,
accessKey: popupButtonAccesskey,
popup: "blockedPopupOptions",
callback: null
}];
const priority = notificationBox.PRIORITY_WARNING_MEDIUM;
notificationBox.appendNotification(message, "popup-blocked",
"chrome://browser/skin/Info.png",
priority, buttons);
}
}
// Record the fact that we've reported this blocked popup, so we don't
// show it again.
gBrowser.selectedBrowser.blockedPopups.reported = true;
}
},
toggleAllowPopupsForSite: function (aEvent)
{
var pm = Services.perms;
var shouldBlock = aEvent.target.getAttribute("block") == "true";
var perm = shouldBlock ? pm.DENY_ACTION : pm.ALLOW_ACTION;
pm.add(gBrowser.currentURI, "popup", perm);
if (!shouldBlock)
this.showAllBlockedPopups(gBrowser.selectedBrowser);
gBrowser.getNotificationBox().removeCurrentNotification();
},
fillPopupList: function (aEvent)
{
// XXXben - rather than using |currentURI| here, which breaks down on multi-framed sites
// we should really walk the blockedPopups and create a list of "allow for <host>"
// menuitems for the common subset of hosts present in the report, this will
// make us frame-safe.
//
// XXXjst - Note that when this is fixed to work with multi-framed sites,
// also back out the fix for bug 343772 where
// nsGlobalWindow::CheckOpenAllow() was changed to also
// check if the top window's location is whitelisted.
let browser = gBrowser.selectedBrowser;
var uri = browser.currentURI;
var blockedPopupAllowSite = document.getElementById("blockedPopupAllowSite");
try {
blockedPopupAllowSite.removeAttribute("hidden");
var pm = Services.perms;
if (pm.testPermission(uri, "popup") == pm.ALLOW_ACTION) {
// Offer an item to block popups for this site, if a whitelist entry exists
// already for it.
let blockString = gNavigatorBundle.getFormattedString("popupBlock", [uri.host || uri.spec]);
blockedPopupAllowSite.setAttribute("label", blockString);
blockedPopupAllowSite.setAttribute("block", "true");
}
else {
// Offer an item to allow popups for this site
let allowString = gNavigatorBundle.getFormattedString("popupAllow", [uri.host || uri.spec]);
blockedPopupAllowSite.setAttribute("label", allowString);
blockedPopupAllowSite.removeAttribute("block");
}
}
catch (e) {
blockedPopupAllowSite.setAttribute("hidden", "true");
}
if (PrivateBrowsingUtils.isWindowPrivate(window))
blockedPopupAllowSite.setAttribute("disabled", "true");
else
blockedPopupAllowSite.removeAttribute("disabled");
let blockedPopupDontShowMessage = document.getElementById("blockedPopupDontShowMessage");
let showMessage = gPrefService.getBoolPref("privacy.popups.showBrowserMessage");
blockedPopupDontShowMessage.setAttribute("checked", !showMessage);
if (aEvent.target.anchorNode.id == "page-report-button") {
aEvent.target.anchorNode.setAttribute("open", "true");
blockedPopupDontShowMessage.setAttribute("label", gNavigatorBundle.getString("popupWarningDontShowFromLocationbar"));
} else {
blockedPopupDontShowMessage.setAttribute("label", gNavigatorBundle.getString("popupWarningDontShowFromMessage"));
}
let blockedPopupsSeparator =
document.getElementById("blockedPopupsSeparator");
blockedPopupsSeparator.setAttribute("hidden", true);
gBrowser.selectedBrowser.retrieveListOfBlockedPopups().then(blockedPopups => {
let foundUsablePopupURI = false;
if (blockedPopups) {
for (let i = 0; i < blockedPopups.length; i++) {
let blockedPopup = blockedPopups[i];
// popupWindowURI will be null if the file picker popup is blocked.
// xxxdz this should make the option say "Show file picker" and do it (Bug 590306)
if (!blockedPopup.popupWindowURIspec)
continue;
var popupURIspec = blockedPopup.popupWindowURIspec;
// Sometimes the popup URI that we get back from the blockedPopup
// isn't useful (for instance, netscape.com's popup URI ends up
// being "http://www.netscape.com", which isn't really the URI of
// the popup they're trying to show). This isn't going to be
// useful to the user, so we won't create a menu item for it.
if (popupURIspec == "" || popupURIspec == "about:blank" ||
popupURIspec == "<self>" ||
popupURIspec == uri.spec)
continue;
// Because of the short-circuit above, we may end up in a situation
// in which we don't have any usable popup addresses to show in
// the menu, and therefore we shouldn't show the separator. However,
// since we got past the short-circuit, we must've found at least
// one usable popup URI and thus we'll turn on the separator later.
foundUsablePopupURI = true;
var menuitem = document.createElement("menuitem");
var label = gNavigatorBundle.getFormattedString("popupShowPopupPrefix",
[popupURIspec]);
menuitem.setAttribute("label", label);
menuitem.setAttribute("oncommand", "gPopupBlockerObserver.showBlockedPopup(event);");
menuitem.setAttribute("popupReportIndex", i);
menuitem.popupReportBrowser = browser;
aEvent.target.appendChild(menuitem);
}
}
// Show the separator if we added any
// showable popup addresses to the menu.
if (foundUsablePopupURI)
blockedPopupsSeparator.removeAttribute("hidden");
}, null);
},
onPopupHiding: function (aEvent) {
if (aEvent.target.anchorNode.id == "page-report-button")
aEvent.target.anchorNode.removeAttribute("open");
this.isPopupHidingTick = true;
setTimeout(() => this.isPopupHidingTick = false, 0);
let item = aEvent.target.lastChild;
while (item && item.getAttribute("observes") != "blockedPopupsSeparator") {
let next = item.previousSibling;
item.parentNode.removeChild(item);
item = next;
}
},
showBlockedPopup: function (aEvent)
{
var target = aEvent.target;
var popupReportIndex = target.getAttribute("popupReportIndex");
let browser = target.popupReportBrowser;
browser.unblockPopup(popupReportIndex);
},
showAllBlockedPopups: function (aBrowser)
{
aBrowser.retrieveListOfBlockedPopups().then(popups => {
for (let i = 0; i < popups.length; i++) {
if (popups[i].popupWindowURIspec)
aBrowser.unblockPopup(i);
}
}, null);
},
editPopupSettings: function ()
{
var host = "";
try {
host = gBrowser.currentURI.host;
}
catch (e) { }
var bundlePreferences = document.getElementById("bundle_preferences");
var params = { blockVisible : false,
sessionVisible : false,
allowVisible : true,
prefilledHost : host,
permissionType : "popup",
windowTitle : bundlePreferences.getString("popuppermissionstitle"),
introText : bundlePreferences.getString("popuppermissionstext") };
var existingWindow = Services.wm.getMostRecentWindow("Browser:Permissions");
if (existingWindow) {
existingWindow.initWithParams(params);
existingWindow.focus();
}
else
window.openDialog("chrome://browser/content/preferences/permissions.xul",
"_blank", "resizable,dialog=no,centerscreen", params);
},
dontShowMessage: function ()
{
var showMessage = gPrefService.getBoolPref("privacy.popups.showBrowserMessage");
gPrefService.setBoolPref("privacy.popups.showBrowserMessage", !showMessage);
gBrowser.getNotificationBox().removeCurrentNotification();
}
};
function gKeywordURIFixup({ target: browser, data: fixupInfo }) {
let deserializeURI = (spec) => spec ? makeURI(spec) : null;
// We get called irrespective of whether we did a keyword search, or
// whether the original input would be vaguely interpretable as a URL,
// so figure that out first.
let alternativeURI = deserializeURI(fixupInfo.fixedURI);
if (!fixupInfo.keywordProviderName || !alternativeURI || !alternativeURI.host) {
return;
}
// At this point we're still only just about to load this URI.
// When the async DNS lookup comes back, we may be in any of these states:
// 1) still on the previous URI, waiting for the preferredURI (keyword
// search) to respond;
// 2) at the keyword search URI (preferredURI)
// 3) at some other page because the user stopped navigation.
// We keep track of the currentURI to detect case (1) in the DNS lookup
// callback.
let previousURI = browser.currentURI;
let preferredURI = deserializeURI(fixupInfo.preferredURI);
// now swap for a weak ref so we don't hang on to browser needlessly
// even if the DNS query takes forever
let weakBrowser = Cu.getWeakReference(browser);
browser = null;
// Additionally, we need the host of the parsed url
let hostName = alternativeURI.host;
// and the ascii-only host for the pref:
let asciiHost = alternativeURI.asciiHost;
// Normalize out a single trailing dot - NB: not using endsWith/lastIndexOf
// because we need to be sure this last dot is the *only* dot, too.
// More generally, this is used for the pref and should stay in sync with
// the code in nsDefaultURIFixup::KeywordURIFixup .
if (asciiHost.indexOf('.') == asciiHost.length - 1) {
asciiHost = asciiHost.slice(0, -1);
}
let isIPv4Address = host => {
let parts = host.split(".");
if (parts.length != 4) {
return false;
}
return parts.every(part => {
let n = parseInt(part, 10);
return n >= 0 && n <= 255;
});
};
// Avoid showing fixup information if we're suggesting an IP. Note that
// decimal representations of IPs are normalized to a 'regular'
// dot-separated IP address by network code, but that only happens for
// numbers that don't overflow. Longer numbers do not get normalized,
// but still work to access IP addresses. So for instance,
// 1097347366913 (ff7f000001) gets resolved by using the final bytes,
// making it the same as 7f000001, which is 127.0.0.1 aka localhost.
// While 2130706433 would get normalized by network, 1097347366913
// does not, and we have to deal with both cases here:
if (isIPv4Address(asciiHost) || /^(?:\d+|0x[a-f0-9]+)$/i.test(asciiHost))
return;
let onLookupComplete = (request, record, status) => {
let browser = weakBrowser.get();
if (!Components.isSuccessCode(status) || !browser)
return;
let currentURI = browser.currentURI;
// If we're in case (3) (see above), don't show an info bar.
if (!currentURI.equals(previousURI) &&
!currentURI.equals(preferredURI)) {
return;
}
// show infobar offering to visit the host
let notificationBox = gBrowser.getNotificationBox(browser);
if (notificationBox.getNotificationWithValue("keyword-uri-fixup"))
return;
let message = gNavigatorBundle.getFormattedString(
"keywordURIFixup.message", [hostName]);
let yesMessage = gNavigatorBundle.getFormattedString(
"keywordURIFixup.goTo", [hostName])
let buttons = [
{
label: yesMessage,
accessKey: gNavigatorBundle.getString("keywordURIFixup.goTo.accesskey"),
callback: function() {
// Do not set this preference while in private browsing.
if (!PrivateBrowsingUtils.isWindowPrivate(window)) {
let pref = "browser.fixup.domainwhitelist." + asciiHost;
Services.prefs.setBoolPref(pref, true);
}
openUILinkIn(alternativeURI.spec, "current");
}
},
{
label: gNavigatorBundle.getString("keywordURIFixup.dismiss"),
accessKey: gNavigatorBundle.getString("keywordURIFixup.dismiss.accesskey"),
callback: function() {
let notification = notificationBox.getNotificationWithValue("keyword-uri-fixup");
notificationBox.removeNotification(notification, true);
}
}
];
let notification =
notificationBox.appendNotification(message, "keyword-uri-fixup", null,
notificationBox.PRIORITY_INFO_HIGH,
buttons);
notification.persistence = 1;
};
try {
gDNSService.asyncResolve(hostName, 0, onLookupComplete, Services.tm.mainThread);
} catch (ex) {
// Do nothing if the URL is invalid (we don't want to show a notification in that case).
if (ex.result != Cr.NS_ERROR_UNKNOWN_HOST) {
// ... otherwise, report:
Cu.reportError(ex);
}
}
}
// A shared function used by both remote and non-remote browser XBL bindings to
// load a URI or redirect it to the correct process.
function _loadURIWithFlags(browser, uri, params) {
if (!uri) {
uri = "about:blank";
}
let flags = params.flags || 0;
let referrer = params.referrerURI;
let referrerPolicy = ('referrerPolicy' in params ? params.referrerPolicy :
Ci.nsIHttpChannel.REFERRER_POLICY_DEFAULT);
let postData = params.postData;
let wasRemote = browser.isRemoteBrowser;
let process = browser.isRemoteBrowser ? Ci.nsIXULRuntime.PROCESS_TYPE_CONTENT
: Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT;
let mustChangeProcess = gMultiProcessBrowser &&
!E10SUtils.canLoadURIInProcess(uri, process);
if ((!wasRemote && !mustChangeProcess) ||
(wasRemote && mustChangeProcess)) {
browser.inLoadURI = true;
}
try {
if (!mustChangeProcess) {
if (params.userContextId) {
browser.webNavigation.setOriginAttributesBeforeLoading({ userContextId: params.userContextId });
}
browser.webNavigation.loadURIWithOptions(uri, flags,
referrer, referrerPolicy,
postData, null, null);
} else {
// Check if the current browser is allowed to unload.
let {permitUnload, timedOut} = browser.permitUnload();
if (!timedOut && !permitUnload) {
return;
}
if (postData) {
postData = NetUtil.readInputStreamToString(postData, postData.available());
}
let loadParams = {
uri: uri,
flags: flags,
referrer: referrer ? referrer.spec : null,
referrerPolicy: referrerPolicy,
postData: postData
}
if (params.userContextId) {
loadParams.userContextId = params.userContextId;
}
LoadInOtherProcess(browser, loadParams);
}
} catch (e) {
// If anything goes wrong when switching remoteness, just switch remoteness
// manually and load the URI.
// We might lose history that way but at least the browser loaded a page.
// This might be necessary if SessionStore wasn't initialized yet i.e.
// when the homepage is a non-remote page.
if (mustChangeProcess) {
Cu.reportError(e);
gBrowser.updateBrowserRemotenessByURL(browser, uri);
if (params.userContextId) {
browser.webNavigation.setOriginAttributesBeforeLoading({ userContextId: params.userContextId });
}
browser.webNavigation.loadURIWithOptions(uri, flags, referrer, referrerPolicy,
postData, null, null);
} else {
throw e;
}
} finally {
if ((!wasRemote && !mustChangeProcess) ||
(wasRemote && mustChangeProcess)) {
browser.inLoadURI = false;
}
}
}
// Starts a new load in the browser first switching the browser to the correct
// process
function LoadInOtherProcess(browser, loadOptions, historyIndex = -1) {
let tab = gBrowser.getTabForBrowser(browser);
SessionStore.navigateAndRestore(tab, loadOptions, historyIndex);
}
// Called when a docshell has attempted to load a page in an incorrect process.
// This function is responsible for loading the page in the correct process.
function RedirectLoad({ target: browser, data }) {
// We should only start the redirection if the browser window has finished
// starting up. Otherwise, we should wait until the startup is done.
if (gBrowserInit.delayedStartupFinished) {
LoadInOtherProcess(browser, data.loadOptions, data.historyIndex);
} else {
let delayedStartupFinished = (subject, topic) => {
if (topic == "browser-delayed-startup-finished" &&
subject == window) {
Services.obs.removeObserver(delayedStartupFinished, topic);
LoadInOtherProcess(browser, data.loadOptions, data.historyIndex);
}
};
Services.obs.addObserver(delayedStartupFinished,
"browser-delayed-startup-finished",
false);
}
}
addEventListener("DOMContentLoaded", function onDCL() {
removeEventListener("DOMContentLoaded", onDCL);
// There are some windows, like macBrowserOverlay.xul, that
// load browser.js, but never load tabbrowser.xml. We can ignore
// those cases.
if (!gBrowser || !gBrowser.updateBrowserRemoteness) {
return;
}
window.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(nsIWebNavigation)
.QueryInterface(Ci.nsIDocShellTreeItem).treeOwner
.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIXULWindow)
.XULBrowserWindow = window.XULBrowserWindow;
window.QueryInterface(Ci.nsIDOMChromeWindow).browserDOMWindow =
new nsBrowserAccess();
let initBrowser =
document.getAnonymousElementByAttribute(gBrowser, "anonid", "initialBrowser");
// The window's first argument is a tab if and only if we are swapping tabs.
// We must set the browser's usercontextid before updateBrowserRemoteness(),
// so that the newly created remote tab child has the correct usercontextid.
if (window.arguments) {
let tabToOpen = window.arguments[0];
if (tabToOpen instanceof XULElement && tabToOpen.hasAttribute("usercontextid")) {
initBrowser.setAttribute("usercontextid", tabToOpen.getAttribute("usercontextid"));
}
}
gBrowser.updateBrowserRemoteness(initBrowser, gMultiProcessBrowser);
});
var gBrowserInit = {
delayedStartupFinished: false,
onLoad: function() {
gBrowser.addEventListener("DOMUpdatePageReport", gPopupBlockerObserver, false);
Services.obs.addObserver(gPluginHandler.NPAPIPluginCrashed, "plugin-crashed", false);
window.addEventListener("AppCommand", HandleAppCommandEvent, true);
// These routines add message listeners. They must run before
// loading the frame script to ensure that we don't miss any
// message sent between when the frame script is loaded and when
// the listener is registered.
DOMLinkHandler.init();
gPageStyleMenu.init();
LanguageDetectionListener.init();
BrowserOnClick.init();
FeedHandler.init();
DevEdition.init();
AboutPrivateBrowsingListener.init();
TrackingProtection.init();
RefreshBlocker.init();
CaptivePortalWatcher.init();
let mm = window.getGroupMessageManager("browsers");
mm.loadFrameScript("chrome://browser/content/tab-content.js", true);
mm.loadFrameScript("chrome://browser/content/content.js", true);
mm.loadFrameScript("chrome://browser/content/content-UITour.js", true);
mm.loadFrameScript("chrome://global/content/manifestMessages.js", true);