Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code

Side by Side Diff: background.js

Issue 16067002: Added Safari Support (Closed)
Patch Set: Removed absolute URL fix for Safari (this is done by the buildtools now), introduced browser specif… Created Oct. 31, 2013, 10:50 a.m.
Left:
Right:
Use n/p to move between diff chunks; N/P to move between comments.
Jump to:
View unified diff | Download patch
OLDNEW
1 /* 1 /*
2 * This file is part of Adblock Plus <http://adblockplus.org/>, 2 * This file is part of Adblock Plus <http://adblockplus.org/>,
3 * Copyright (C) 2006-2013 Eyeo GmbH 3 * Copyright (C) 2006-2013 Eyeo GmbH
4 * 4 *
5 * Adblock Plus is free software: you can redistribute it and/or modify 5 * Adblock Plus is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 3 as 6 * it under the terms of the GNU General Public License version 3 as
7 * published by the Free Software Foundation. 7 * published by the Free Software Foundation.
8 * 8 *
9 * Adblock Plus is distributed in the hope that it will be useful, 9 * Adblock Plus is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
(...skipping 95 matching lines...) Expand 10 before | Expand all | Expand 10 after
106 106
107 var result = defaultMatcher.matchesAny(url, type || "DOCUMENT", extractHostFro mURL(parentUrl || url), false); 107 var result = defaultMatcher.matchesAny(url, type || "DOCUMENT", extractHostFro mURL(parentUrl || url), false);
108 return (result instanceof WhitelistFilter ? result : null); 108 return (result instanceof WhitelistFilter ? result : null);
109 } 109 }
110 110
111 var activeNotification = null; 111 var activeNotification = null;
112 112
113 // Adds or removes page action icon according to options. 113 // Adds or removes page action icon according to options.
114 function refreshIconAndContextMenu(tab) 114 function refreshIconAndContextMenu(tab)
115 { 115 {
116 // The tab could have been closed by the time this function is called 116 if(!/^https?:/.test(tab.url))
117 if(!tab)
118 return; 117 return;
119 118
120 var excluded = isWhitelisted(tab.url); 119 var excluded = isWhitelisted(tab.url);
121 var iconFilename = excluded ? "icons/abp-19-whitelisted.png" : "icons/abp-19.p ng"; 120 var iconFilename;
122 121
123 if (activeNotification) 122 // If the page is whitelisted use the grayscale version of the icon
124 startIconAnimation(tab, iconFilename); 123 // for that tab, except for Safari where all icons are grayscale
124 // already and where icons aren't per tab.
125 if ("safari" in window || !excluded)
126 iconFilename = "icons/abp-18.png";
125 else 127 else
126 chrome.pageAction.setIcon({tabId: tab.id, path: iconFilename}); 128 iconFilename = "icons/abp-18-whitelisted.png";
127 129
128 // Only show icon for pages we can influence (http: and https:) 130 tab.pageAction.setIcon(iconFilename);
129 if(/^https?:/.test(tab.url)) 131 tab.pageAction.setTitle("Adblock Plus");
130 {
131 chrome.pageAction.setTitle({tabId: tab.id, title: "Adblock Plus"});
132 if ("shouldShowIcon" in localStorage && localStorage["shouldShowIcon"] == "f alse")
133 chrome.pageAction.hide(tab.id);
134 else
135 chrome.pageAction.show(tab.id);
136 132
133 iconAnimation.registerTab(tab, iconFilename);
134
135 if (localStorage.shouldShowIcon == "false")
136 tab.pageAction.hide();
137 else
138 tab.pageAction.show();
139
140 if ("chrome" in window) // TODO: Implement context menus for Safari
137 // Set context menu status according to whether current tab has whitelisted domain 141 // Set context menu status according to whether current tab has whitelisted domain
138 if (excluded) 142 if (excluded)
139 chrome.contextMenus.removeAll(); 143 chrome.contextMenus.removeAll();
140 else 144 else
141 showContextMenu(); 145 showContextMenu();
142 }
143 } 146 }
144 147
145 /** 148 /**
146 * Old versions stored filter data in the localStorage object, this will import 149 * Old versions stored filter data in the localStorage object, this will import
147 * it into FilterStorage properly. 150 * it into FilterStorage properly.
148 */ 151 */
149 function importOldData() 152 function importOldData()
150 { 153 {
151 function addSubscription(url, title) 154 function addSubscription(url, title)
152 { 155 {
(...skipping 207 matching lines...) Expand 10 before | Expand all | Expand 10 after
360 } 363 }
361 else 364 else
362 addAcceptable = false; 365 addAcceptable = false;
363 } 366 }
364 367
365 if (!addSubscription && !addAcceptable) 368 if (!addSubscription && !addAcceptable)
366 return; 369 return;
367 370
368 function notifyUser() 371 function notifyUser()
369 { 372 {
370 chrome.tabs.create({ 373 ext.windows.getLastFocused(function(win) {
371 url: chrome.extension.getURL("firstRun.html") 374 win.openTab(ext.getURL("firstRun.html"));
372 }); 375 });
373 } 376 }
374 377
375 if (addSubscription) 378 if (addSubscription)
376 { 379 {
377 // Load subscriptions data 380 // Load subscriptions data
378 var request = new XMLHttpRequest(); 381 var request = new XMLHttpRequest();
379 request.open("GET", "subscriptions.xml"); 382 request.open("GET", "subscriptions.xml");
380 request.addEventListener("load", function() 383 request.addEventListener("load", function()
381 { 384 {
(...skipping 17 matching lines...) Expand all
399 notifyUser(); 402 notifyUser();
400 } 403 }
401 404
402 // Set up context menu for user selection of elements to block 405 // Set up context menu for user selection of elements to block
403 function showContextMenu() 406 function showContextMenu()
404 { 407 {
405 chrome.contextMenus.removeAll(function() 408 chrome.contextMenus.removeAll(function()
406 { 409 {
407 if(typeof localStorage["shouldShowBlockElementMenu"] == "string" && localSto rage["shouldShowBlockElementMenu"] == "true") 410 if(typeof localStorage["shouldShowBlockElementMenu"] == "string" && localSto rage["shouldShowBlockElementMenu"] == "true")
408 { 411 {
409 chrome.contextMenus.create({'title': chrome.i18n.getMessage('block_element '), 'contexts': ['image', 'video', 'audio'], 'onclick': function(info, tab) 412 chrome.contextMenus.create({"title": chrome.i18n.getMessage("block_element "), "contexts": ["image", "video", "audio"], "onclick": function(info, tab)
410 { 413 {
411 if(info.srcUrl) 414 if(info.srcUrl)
412 chrome.tabs.sendRequest(tab.id, {reqtype: "clickhide-new-filter", fi lter: info.srcUrl}); 415 chrome.tabs.sendRequest(tab.id, {reqtype: "clickhide-new-filter", fi lter: info.srcUrl});
413 }}); 416 }});
414 } 417 }
415 }); 418 });
416 } 419 }
417 420
418 /**
419 * Opens Options window or focuses an existing one.
420 * @param {Function} callback function to be called with the window object of
421 * the Options window
422 */
423 function openOptions(callback) 421 function openOptions(callback)
424 { 422 {
425 function findOptions(selectTab) 423 ext.windows.getLastFocused(function(win)
426 { 424 {
427 var views = chrome.extension.getViews({type: "tab"}); 425 win.getAllTabs(function(tabs)
428 for (var i = 0; i < views.length; i++) 426 {
429 if ("startSubscriptionSelection" in views[i]) 427 var optionsUrl = ext.getURL("options.html");
430 return views[i];
431 428
432 return null; 429 for (var i = 0; i < tabs.length; i++)
433 } 430 if (tabs[i].url == optionsUrl)
431 {
432 tabs[i].activate();
433 if (callback)
434 callback(tabs[i]);
435 return;
436 }
434 437
435 function selectOptionsTab() 438 win.openTab(optionsUrl, callback && function(tab) {
436 { 439 tab.onCompleted.addListener(callback);
437 chrome.windows.getAll({populate: true}, function(windows) 440 });
438 {
439 var url = chrome.extension.getURL("options.html");
440 for (var i = 0; i < windows.length; i++)
441 for (var j = 0; j < windows[i].tabs.length; j++)
442 if (windows[i].tabs[j].url == url)
443 chrome.tabs.update(windows[i].tabs[j].id, {selected: true});
444 });
445 }
446
447 var view = findOptions();
448 if (view)
449 {
450 selectOptionsTab();
451 callback(view);
452 }
453 else
454 {
455 var onLoad = function()
456 {
457 var view = findOptions();
458 if (view)
459 callback(view);
460 };
461
462 chrome.tabs.create({url: chrome.extension.getURL("options.html")}, function( tab)
463 {
464 if (tab.status == "complete")
465 onLoad();
466 else
467 {
468 var id = tab.id;
469 var listener = function(tabId, changeInfo, tab)
470 {
471 if (tabId == id && changeInfo.status == "complete")
472 {
473 chrome.tabs.onUpdated.removeListener(listener);
474 onLoad();
475 }
476 };
477 chrome.tabs.onUpdated.addListener(listener);
478 }
479 });
480 }
481 }
482
483 var iconAnimationTimer = null;
484 var animatedIconTab = null;
485
486 function stopIconAnimation()
487 {
488 if (!iconAnimationTimer)
489 return;
490
491 clearTimeout(iconAnimationTimer);
492 iconAnimationTimer = null;
493 animatedIconTab = null;
494 }
495
496 function loadImages(imageFiles, callback)
497 {
498 var images = {};
499 var imagesLoaded = 0;
500 imageFiles.forEach(function(imageFile)
501 {
502 var image = new Image();
503 image.src = imageFile;
504 image.addEventListener("load", function()
505 {
506 images[imageFile] = image;
507 if (++imagesLoaded === imageFiles.length)
508 callback(images);
509 }); 441 });
510 }); 442 });
511 } 443 }
512 444
513 function startIconAnimation(tab, iconPath)
514 {
515 stopIconAnimation();
516 animatedIconTab = tab;
517
518 var severitySuffix = activeNotification.severity === "critical"
519 ? "critical" : "information";
520 var notificationIconPath = "icons/notification-" + severitySuffix + ".png";
521 var iconFiles = [iconPath, notificationIconPath];
522 loadImages(iconFiles, function(images)
523 {
524 var icon = images[iconPath];
525 var notificationIcon = images[notificationIconPath];
526
527 var canvas = document.createElement("canvas");
528 canvas.width = icon.width;
529 canvas.height = icon.height;
530 var context = canvas.getContext("2d");
531
532 var currentFrame = 0;
533 var frameOpacities = [0, 0.2, 0.4, 0.6, 0.8,
534 1, 1, 1, 1, 1,
535 0.8, 0.6, 0.4, 0.2, 0];
536
537 function animationStep()
538 {
539 var opacity = frameOpacities[currentFrame];
540 context.clearRect(0, 0, canvas.width, canvas.height);
541 context.globalAlpha = 1;
542 context.drawImage(icon, 0, 0);
543 context.globalAlpha = opacity;
544 context.drawImage(notificationIcon, 0, 0);
545 var imageData = context.getImageData(0, 0, canvas.width, canvas.height);
546 chrome.pageAction.setIcon({tabId: tab.id, imageData: imageData});
547
548 var interval;
549 currentFrame++;
550 if (currentFrame < frameOpacities.length)
551 {
552 var duration = 3000;
553 interval = duration / frameOpacities.length;
554 }
555 else
556 {
557 currentFrame = 0;
558 interval = 10000;
559 }
560 iconAnimationTimer = setTimeout(animationStep, interval);
561 }
562 animationStep();
563 });
564 }
565
566 function prepareNotificationIconAndPopup() 445 function prepareNotificationIconAndPopup()
567 { 446 {
568 activeNotification.onClicked = function() 447 activeNotification.onClicked = function()
569 { 448 {
570 var tab = animatedIconTab; 449 iconAnimation.stop();
571 stopIconAnimation();
572 activeNotification = null; 450 activeNotification = null;
573 refreshIconAndContextMenu(tab);
574 }; 451 };
575 452
576 chrome.windows.getLastFocused({populate: true}, function(window) 453 iconAnimation.update(activeNotification.severity);
577 {
578 chrome.tabs.query({active: true, windowId: window.id}, function(tabs)
579 {
580 tabs.forEach(refreshIconAndContextMenu);
581 });
582 });
583 } 454 }
584 455
585 function showNotification(notification) 456 function showNotification(notification)
586 { 457 {
587 activeNotification = notification; 458 activeNotification = notification;
588 459
589 if (activeNotification.severity === "critical" 460 if (activeNotification.severity === "critical"
590 && typeof webkitNotifications !== "undefined") 461 && typeof webkitNotifications !== "undefined")
591 { 462 {
592 var notification = webkitNotifications.createHTMLNotification("notification. html"); 463 var notification = webkitNotifications.createHTMLNotification("notification. html");
593 notification.show(); 464 notification.show();
594 notification.addEventListener("close", prepareNotificationIconAndPopup); 465 notification.addEventListener("close", prepareNotificationIconAndPopup);
595 } 466 }
596 else 467 else
597 prepareNotificationIconAndPopup(); 468 prepareNotificationIconAndPopup();
598 } 469 }
599 470
600 /** 471 /**
601 * This function is a hack - we only know the tabId and document URL for a 472 * This function is a hack - we only know the tabId and document URL for a
602 * message but we need to know the frame ID. Try to find it in webRequest's 473 * message but we need to know the frame ID. Try to find it in webRequest"s
603 * frame data. 474 * frame data.
604 */ 475 */
605 function getFrameId(tabId, url) 476 function getFrameId(tab, url)
606 { 477 {
607 if (tabId in frames) 478 for (var frameId in frames.get(tab))
608 { 479 if (getFrameUrl(tab, frameId) == url)
609 for (var f in frames[tabId]) 480 return frameId;
610 {
611 if (getFrameUrl(tabId, f) == url)
612 return f;
613 }
614 }
615 return -1; 481 return -1;
616 } 482 }
617 483
618 chrome.extension.onRequest.addListener(function(request, sender, sendResponse) 484 ext.onMessage.addListener(function (msg, sender, sendResponse)
619 { 485 {
620 switch (request.reqtype) 486 switch (msg.type)
621 { 487 {
622 case "get-settings": 488 case "get-settings":
623 var hostDomain = null; 489 var hostDomain = null;
624 var selectors = null; 490 var selectors = null;
625 491
626 var tabId = -1; 492 var frameId = sender.tab ? getFrameId(sender.tab, msg.frameUrl) : -1;
627 var frameId = -1; 493 var enabled = false;
628 if (sender.tab)
629 {
630 tabId = sender.tab.id;
631 frameId = getFrameId(tabId, request.frameUrl);
632 }
633 494
634 var enabled = !isFrameWhitelisted(tabId, frameId, "DOCUMENT") && !isFrameW hitelisted(tabId, frameId, "ELEMHIDE"); 495 if (!isFrameWhitelisted(sender.tab, frameId, "DOCUMENT"))
635 if (enabled && request.selectors) 496 if (!isFrameWhitelisted(sender.tab, frameId, "ELEMHIDE")) {
636 { 497 var enabled = true;
637 var noStyleRules = false; 498
638 var host = extractHostFromURL(request.frameUrl); 499 if (msg.selectors)
639 hostDomain = getBaseDomain(host);
640 for (var i = 0; i < noStyleRulesHosts.length; i++)
641 { 500 {
642 var noStyleHost = noStyleRulesHosts[i]; 501 var noStyleRules = false;
643 if (host == noStyleHost || (host.length > noStyleHost.length && 502 var host = extractHostFromURL(msg.frameUrl);
644 host.substr(host.length - noStyleHost.leng th - 1) == "." + noStyleHost)) 503 hostDomain = getBaseDomain(host);
504 for (var i = 0; i < noStyleRulesHosts.length; i++)
645 { 505 {
646 noStyleRules = true; 506 var noStyleHost = noStyleRulesHosts[i];
507 if (host == noStyleHost || (host.length > noStyleHost.length &&
508 host.substr(host.length - noStyleHost.le ngth - 1) == "." + noStyleHost))
509 {
510 noStyleRules = true;
511 }
647 } 512 }
648 } 513 selectors = ElemHide.getSelectorsForDomain(host, false);
649 selectors = ElemHide.getSelectorsForDomain(host, false); 514 if (noStyleRules)
650 if (noStyleRules)
651 {
652 selectors = selectors.filter(function(s)
653 { 515 {
654 return !/\[style[\^\$]?=/.test(s); 516 selectors = selectors.filter(function(s)
655 }); 517 {
518 return !/\[style[\^\$]?=/.test(s);
519 });
520 }
656 } 521 }
657 } 522 }
658 523
659 sendResponse({enabled: enabled, hostDomain: hostDomain, selectors: selecto rs}); 524 sendResponse({enabled: enabled, hostDomain: hostDomain, selectors: selecto rs});
660 break; 525 break;
661 case "should-collapse": 526 case "should-collapse":
662 var tabId = -1; 527 var frameId = sender.tab ? getFrameId(sender.tab, msg.documentUrl) : -1;
663 var frameId = -1;
664 if (sender.tab)
665 {
666 tabId = sender.tab.id;
667 frameId = getFrameId(tabId, request.documentUrl);
668 }
669 528
670 if (isFrameWhitelisted(tabId, frameId, "DOCUMENT")) 529 if (isFrameWhitelisted(sender.tab, frameId, "DOCUMENT"))
671 { 530 {
672 sendResponse(false); 531 sendResponse(false);
673 break; 532 break;
674 } 533 }
675 534
676 var requestHost = extractHostFromURL(request.url); 535 var requestHost = extractHostFromURL(msg.url);
677 var documentHost = extractHostFromURL(request.documentUrl); 536 var documentHost = extractHostFromURL(msg.documentUrl);
678 var thirdParty = isThirdParty(requestHost, documentHost); 537 var thirdParty = isThirdParty(requestHost, documentHost);
679 var filter = defaultMatcher.matchesAny(request.url, request.type, document Host, thirdParty); 538 var filter = defaultMatcher.matchesAny(msg.url, msg.mediatype, documentHos t, thirdParty);
680 if (filter instanceof BlockingFilter) 539 if (filter instanceof BlockingFilter)
681 { 540 {
682 var collapse = filter.collapse; 541 var collapse = filter.collapse;
683 if (collapse == null) 542 if (collapse == null)
684 collapse = (localStorage.hidePlaceholders != "false"); 543 collapse = (localStorage.hidePlaceholders != "false");
685 sendResponse(collapse); 544 sendResponse(collapse);
686 } 545 }
687 else 546 else
688 sendResponse(false); 547 sendResponse(false);
689 break; 548 break;
690 case "get-domain-enabled-state": 549 case "get-domain-enabled-state":
691 // Returns whether this domain is in the exclusion list. 550 // Returns whether this domain is in the exclusion list.
692 // The page action popup asks us this. 551 // The page action popup asks us this.
693 if(sender.tab) 552 if(sender.tab)
694 { 553 {
695 sendResponse({enabled: !isWhitelisted(sender.tab.url)}); 554 sendResponse({enabled: !isWhitelisted(sender.tab.url)});
696 return; 555 return;
697 } 556 }
698 break; 557 break;
699 case "add-filters": 558 case "add-filters":
700 if (request.filters && request.filters.length) 559 if (msg.filters && msg.filters.length)
701 { 560 {
702 for (var i = 0; i < request.filters.length; i++) 561 for (var i = 0; i < msg.filters.length; i++)
703 FilterStorage.addFilter(Filter.fromText(request.filters[i])); 562 FilterStorage.addFilter(Filter.fromText(msg.filters[i]));
704 } 563 }
705 break; 564 break;
706 case "add-subscription": 565 case "add-subscription":
707 openOptions(function(view) 566 openOptions(function(tab) { tab.sendMessage(msg); });
708 {
709 view.startSubscriptionSelection(request.title, request.url);
710 });
711 break; 567 break;
712 case "forward": 568 case "forward":
713 chrome.tabs.sendRequest(sender.tab.id, request.request, sendResponse); 569 tab.sendMessage(msg.payload, sendResponse);
714 break; 570 break;
715 default: 571 default:
716 sendResponse({}); 572 sendResponse({});
717 break; 573 break;
718 } 574 }
719 }); 575 });
720 576
721 // Show icon as page action for all tabs that already exist 577 // Show icon as page action for all tabs that already exist
722 chrome.windows.getAll({populate: true}, function(windows) 578 ext.windows.getAll(function(windows)
723 { 579 {
724 for (var i = 0; i < windows.length; i++) 580 for (var i = 0; i < windows.length; i++)
725 for (var j = 0; j < windows[i].tabs.length; j++) 581 windows[i].getAllTabs(function(tabs)
726 refreshIconAndContextMenu(windows[i].tabs[j]); 582 {
583 tabs.forEach(refreshIconAndContextMenu);
584 });
727 }); 585 });
728 586
729 // Update icon if a tab changes location 587 // Update icon if a tab changes location
730 chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) 588 ext.tabs.onBeforeNavigate.addListener(function(tab)
731 { 589 {
732 chrome.tabs.sendRequest(tabId, {reqtype: "clickhide-deactivate"}) 590 tab.sendMessage({type: "clickhide-deactivate"});
733 if(changeInfo.status == "loading") 591 refreshIconAndContextMenu(tab);
734 refreshIconAndContextMenu(tab);
735 });
736
737 // Refresh icon when switching tabs or windows
738 chrome.tabs.onActivated.addListener(function(activeInfo)
739 {
740 refreshIconAndContextMenu(animatedIconTab);
741 chrome.tabs.get(activeInfo.tabId, refreshIconAndContextMenu);
742 });
743 chrome.windows.onFocusChanged.addListener(function(windowId)
744 {
745 refreshIconAndContextMenu(animatedIconTab);
746 chrome.tabs.query({active: true, windowId: windowId}, function(tabs)
747 {
748 tabs.forEach(refreshIconAndContextMenu);
749 });
750 }); 592 });
751 593
752 setTimeout(function() 594 setTimeout(function()
753 { 595 {
754 var notificationToShow = Notification.getNextToShow(); 596 var notificationToShow = Notification.getNextToShow();
755 if (notificationToShow) 597 if (notificationToShow)
756 showNotification(notificationToShow); 598 showNotification(notificationToShow);
757 }, 3 * 60 * 1000); 599 }, 3 * 60 * 1000);
OLDNEW
« _locales/en_US/messages.json ('K') | « _locales/en_US/messages.json ('k') | block.js » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld