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: Fixed js errors in popup.html. Created Nov. 11, 2013, 5 p.m.
Left:
Right:
Use n/p to move between diff chunks; N/P to move between comments.
Jump to:
View unified diff | Download patch
« no previous file with comments | « no previous file | block.js » ('j') | safari/common.js » ('J')
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
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 iconFilename = "icons/abp-";
121 var iconFilename = excluded ? "icons/abp-19-whitelisted.png" : "icons/abp-19.p ng"; 120 if ("safari" in window)
121 iconFilename += "16";
122 else
123 {
124 iconFilename += "19";
122 125
123 if (activeNotification) 126 // If the page is whitelisted use the grayscale version of the icon
124 startIconAnimation(tab, iconFilename); 127 // for that tab, except for Safari where all icons are grayscale
128 // already and where icons aren't per tab.
129 var excluded = isWhitelisted(tab.url);
130 if (excluded)
131 iconFilename += "-whitelisted";
132 }
133 iconFilename += ".png";
134
135 tab.pageAction.setIcon(iconFilename);
136 tab.pageAction.setTitle("Adblock Plus");
137
138 iconAnimation.registerTab(tab, iconFilename);
139
140 if (localStorage.shouldShowIcon == "false")
141 tab.pageAction.hide();
125 else 142 else
126 chrome.pageAction.setIcon({tabId: tab.id, path: iconFilename}); 143 tab.pageAction.show();
127 144
128 // Only show icon for pages we can influence (http: and https:) 145 if ("chrome" in window) // TODO: Implement context menus for Safari
129 if(/^https?:/.test(tab.url))
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
137 // Set context menu status according to whether current tab has whitelisted domain 146 // Set context menu status according to whether current tab has whitelisted domain
138 if (excluded) 147 if (excluded)
139 chrome.contextMenus.removeAll(); 148 chrome.contextMenus.removeAll();
140 else 149 else
141 showContextMenu(); 150 showContextMenu();
142 }
143 } 151 }
144 152
145 /** 153 /**
146 * Old versions stored filter data in the localStorage object, this will import 154 * Old versions stored filter data in the localStorage object, this will import
147 * it into FilterStorage properly. 155 * it into FilterStorage properly.
148 */ 156 */
149 function importOldData() 157 function importOldData()
150 { 158 {
151 function addSubscription(url, title) 159 function addSubscription(url, title)
152 { 160 {
(...skipping 207 matching lines...) Expand 10 before | Expand all | Expand 10 after
360 } 368 }
361 else 369 else
362 addAcceptable = false; 370 addAcceptable = false;
363 } 371 }
364 372
365 if (!addSubscription && !addAcceptable) 373 if (!addSubscription && !addAcceptable)
366 return; 374 return;
367 375
368 function notifyUser() 376 function notifyUser()
369 { 377 {
370 chrome.tabs.create({ 378 ext.windows.getLastFocused(function(win) {
371 url: chrome.extension.getURL("firstRun.html") 379 win.openTab(ext.getURL("firstRun.html"));
372 }); 380 });
373 } 381 }
374 382
375 if (addSubscription) 383 if (addSubscription)
376 { 384 {
377 // Load subscriptions data 385 // Load subscriptions data
378 var request = new XMLHttpRequest(); 386 var request = new XMLHttpRequest();
379 request.open("GET", "subscriptions.xml"); 387 request.open("GET", "subscriptions.xml");
380 request.addEventListener("load", function() 388 request.addEventListener("load", function()
381 { 389 {
(...skipping 17 matching lines...) Expand all
399 notifyUser(); 407 notifyUser();
400 } 408 }
401 409
402 // Set up context menu for user selection of elements to block 410 // Set up context menu for user selection of elements to block
403 function showContextMenu() 411 function showContextMenu()
404 { 412 {
405 chrome.contextMenus.removeAll(function() 413 chrome.contextMenus.removeAll(function()
406 { 414 {
407 if(typeof localStorage["shouldShowBlockElementMenu"] == "string" && localSto rage["shouldShowBlockElementMenu"] == "true") 415 if(typeof localStorage["shouldShowBlockElementMenu"] == "string" && localSto rage["shouldShowBlockElementMenu"] == "true")
408 { 416 {
409 chrome.contextMenus.create({'title': chrome.i18n.getMessage('block_element '), 'contexts': ['image', 'video', 'audio'], 'onclick': function(info, tab) 417 chrome.contextMenus.create({"title": chrome.i18n.getMessage("block_element "), "contexts": ["image", "video", "audio"], "onclick": function(info, tab)
410 { 418 {
411 if(info.srcUrl) 419 if(info.srcUrl)
412 chrome.tabs.sendRequest(tab.id, {reqtype: "clickhide-new-filter", fi lter: info.srcUrl}); 420 chrome.tabs.sendRequest(tab.id, {reqtype: "clickhide-new-filter", fi lter: info.srcUrl});
413 }}); 421 }});
414 } 422 }
415 }); 423 });
416 } 424 }
417 425
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) 426 function openOptions(callback)
424 { 427 {
425 function findOptions(selectTab) 428 ext.windows.getLastFocused(function(win)
426 { 429 {
427 var views = chrome.extension.getViews({type: "tab"}); 430 win.getAllTabs(function(tabs)
428 for (var i = 0; i < views.length; i++) 431 {
429 if ("startSubscriptionSelection" in views[i]) 432 var optionsUrl = ext.getURL("options.html");
430 return views[i];
431 433
432 return null; 434 for (var i = 0; i < tabs.length; i++)
433 } 435 if (tabs[i].url == optionsUrl)
436 {
437 tabs[i].activate();
438 if (callback)
439 callback(tabs[i]);
440 return;
441 }
434 442
435 function selectOptionsTab() 443 win.openTab(optionsUrl, callback && function(tab) {
436 { 444 tab.onCompleted.addListener(callback);
437 chrome.windows.getAll({populate: true}, function(windows) 445 });
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 }); 446 });
510 }); 447 });
511 } 448 }
512 449
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() 450 function prepareNotificationIconAndPopup()
567 { 451 {
568 activeNotification.onClicked = function() 452 activeNotification.onClicked = function()
569 { 453 {
570 var tab = animatedIconTab; 454 iconAnimation.stop();
571 stopIconAnimation();
572 activeNotification = null; 455 activeNotification = null;
573 refreshIconAndContextMenu(tab);
574 }; 456 };
575 457
576 chrome.windows.getLastFocused({populate: true}, function(window) 458 iconAnimation.update(activeNotification.severity);
577 {
578 chrome.tabs.query({active: true, windowId: window.id}, function(tabs)
579 {
580 tabs.forEach(refreshIconAndContextMenu);
581 });
582 });
583 } 459 }
584 460
585 function showNotification(notification) 461 function showNotification(notification)
586 { 462 {
587 activeNotification = notification; 463 activeNotification = notification;
588 464
589 if (activeNotification.severity === "critical" 465 if (activeNotification.severity === "critical"
590 && typeof webkitNotifications !== "undefined") 466 && typeof webkitNotifications !== "undefined")
591 { 467 {
592 var notification = webkitNotifications.createHTMLNotification("notification. html"); 468 var notification = webkitNotifications.createHTMLNotification("notification. html");
593 notification.show(); 469 notification.show();
594 notification.addEventListener("close", prepareNotificationIconAndPopup); 470 notification.addEventListener("close", prepareNotificationIconAndPopup);
595 } 471 }
596 else 472 else
597 prepareNotificationIconAndPopup(); 473 prepareNotificationIconAndPopup();
598 } 474 }
599 475
600 /** 476 /**
601 * This function is a hack - we only know the tabId and document URL for a 477 * 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 478 * message but we need to know the frame ID. Try to find it in webRequest"s
603 * frame data. 479 * frame data.
604 */ 480 */
605 function getFrameId(tabId, url) 481 function getFrameId(tab, url)
606 { 482 {
607 if (tabId in frames) 483 for (var frameId in frames.get(tab))
608 { 484 if (getFrameUrl(tab, frameId) == url)
609 for (var f in frames[tabId]) 485 return frameId;
610 {
611 if (getFrameUrl(tabId, f) == url)
612 return f;
613 }
614 }
615 return -1; 486 return -1;
616 } 487 }
617 488
618 chrome.extension.onRequest.addListener(function(request, sender, sendResponse) 489 ext.onMessage.addListener(function (msg, sender, sendResponse)
619 { 490 {
620 switch (request.reqtype) 491 switch (msg.type)
621 { 492 {
622 case "get-settings": 493 case "get-settings":
623 var hostDomain = null; 494 var hostDomain = null;
624 var selectors = null; 495 var selectors = null;
625 496
626 var tabId = -1; 497 var frameId = sender.tab ? getFrameId(sender.tab, msg.frameUrl) : -1;
627 var frameId = -1; 498 var enabled = false;
628 if (sender.tab)
629 {
630 tabId = sender.tab.id;
631 frameId = getFrameId(tabId, request.frameUrl);
632 }
633 499
634 var enabled = !isFrameWhitelisted(tabId, frameId, "DOCUMENT") && !isFrameW hitelisted(tabId, frameId, "ELEMHIDE"); 500 if (!isFrameWhitelisted(sender.tab, frameId, "DOCUMENT"))
635 if (enabled && request.selectors) 501 if (!isFrameWhitelisted(sender.tab, frameId, "ELEMHIDE")) {
636 { 502 var enabled = true;
637 var noStyleRules = false; 503
638 var host = extractHostFromURL(request.frameUrl); 504 if (msg.selectors)
639 hostDomain = getBaseDomain(host);
640 for (var i = 0; i < noStyleRulesHosts.length; i++)
641 { 505 {
642 var noStyleHost = noStyleRulesHosts[i]; 506 var noStyleRules = false;
643 if (host == noStyleHost || (host.length > noStyleHost.length && 507 var host = extractHostFromURL(msg.frameUrl);
644 host.substr(host.length - noStyleHost.leng th - 1) == "." + noStyleHost)) 508 hostDomain = getBaseDomain(host);
509 for (var i = 0; i < noStyleRulesHosts.length; i++)
645 { 510 {
646 noStyleRules = true; 511 var noStyleHost = noStyleRulesHosts[i];
512 if (host == noStyleHost || (host.length > noStyleHost.length &&
513 host.substr(host.length - noStyleHost.le ngth - 1) == "." + noStyleHost))
514 {
515 noStyleRules = true;
516 }
647 } 517 }
648 } 518 selectors = ElemHide.getSelectorsForDomain(host, false);
649 selectors = ElemHide.getSelectorsForDomain(host, false); 519 if (noStyleRules)
650 if (noStyleRules)
651 {
652 selectors = selectors.filter(function(s)
653 { 520 {
654 return !/\[style[\^\$]?=/.test(s); 521 selectors = selectors.filter(function(s)
655 }); 522 {
523 return !/\[style[\^\$]?=/.test(s);
524 });
525 }
656 } 526 }
657 } 527 }
658 528
659 sendResponse({enabled: enabled, hostDomain: hostDomain, selectors: selecto rs}); 529 sendResponse({enabled: enabled, hostDomain: hostDomain, selectors: selecto rs});
660 break; 530 break;
661 case "should-collapse": 531 case "should-collapse":
662 var tabId = -1; 532 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 533
670 if (isFrameWhitelisted(tabId, frameId, "DOCUMENT")) 534 if (isFrameWhitelisted(sender.tab, frameId, "DOCUMENT"))
671 { 535 {
672 sendResponse(false); 536 sendResponse(false);
673 break; 537 break;
674 } 538 }
675 539
676 var requestHost = extractHostFromURL(request.url); 540 var requestHost = extractHostFromURL(msg.url);
677 var documentHost = extractHostFromURL(request.documentUrl); 541 var documentHost = extractHostFromURL(msg.documentUrl);
678 var thirdParty = isThirdParty(requestHost, documentHost); 542 var thirdParty = isThirdParty(requestHost, documentHost);
679 var filter = defaultMatcher.matchesAny(request.url, request.type, document Host, thirdParty); 543 var filter = defaultMatcher.matchesAny(msg.url, msg.mediatype, documentHos t, thirdParty);
680 if (filter instanceof BlockingFilter) 544 if (filter instanceof BlockingFilter)
681 { 545 {
682 var collapse = filter.collapse; 546 var collapse = filter.collapse;
683 if (collapse == null) 547 if (collapse == null)
684 collapse = (localStorage.hidePlaceholders != "false"); 548 collapse = (localStorage.hidePlaceholders != "false");
685 sendResponse(collapse); 549 sendResponse(collapse);
686 } 550 }
687 else 551 else
688 sendResponse(false); 552 sendResponse(false);
689 break; 553 break;
690 case "get-domain-enabled-state": 554 case "get-domain-enabled-state":
691 // Returns whether this domain is in the exclusion list. 555 // Returns whether this domain is in the exclusion list.
692 // The page action popup asks us this. 556 // The page action popup asks us this.
693 if(sender.tab) 557 if(sender.tab)
694 { 558 {
695 sendResponse({enabled: !isWhitelisted(sender.tab.url)}); 559 sendResponse({enabled: !isWhitelisted(sender.tab.url)});
696 return; 560 return;
697 } 561 }
698 break; 562 break;
699 case "add-filters": 563 case "add-filters":
700 if (request.filters && request.filters.length) 564 if (msg.filters && msg.filters.length)
701 { 565 {
702 for (var i = 0; i < request.filters.length; i++) 566 for (var i = 0; i < msg.filters.length; i++)
703 FilterStorage.addFilter(Filter.fromText(request.filters[i])); 567 FilterStorage.addFilter(Filter.fromText(msg.filters[i]));
704 } 568 }
705 break; 569 break;
706 case "add-subscription": 570 case "add-subscription":
707 openOptions(function(view) 571 openOptions(function(tab) { tab.sendMessage(msg); });
708 {
709 view.startSubscriptionSelection(request.title, request.url);
710 });
711 break; 572 break;
712 case "forward": 573 case "forward":
713 chrome.tabs.sendRequest(sender.tab.id, request.request, sendResponse); 574 tab.sendMessage(msg.payload, sendResponse);
714 break; 575 break;
715 default: 576 default:
716 sendResponse({}); 577 sendResponse({});
717 break; 578 break;
718 } 579 }
719 }); 580 });
720 581
721 // Show icon as page action for all tabs that already exist 582 // Show icon as page action for all tabs that already exist
722 chrome.windows.getAll({populate: true}, function(windows) 583 ext.windows.getAll(function(windows)
723 { 584 {
724 for (var i = 0; i < windows.length; i++) 585 for (var i = 0; i < windows.length; i++)
725 for (var j = 0; j < windows[i].tabs.length; j++) 586 windows[i].getAllTabs(function(tabs)
726 refreshIconAndContextMenu(windows[i].tabs[j]); 587 {
588 tabs.forEach(refreshIconAndContextMenu);
589 });
727 }); 590 });
728 591
729 // Update icon if a tab changes location 592 // Update icon if a tab changes location
730 chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) 593 ext.tabs.onBeforeNavigate.addListener(function(tab)
731 { 594 {
732 chrome.tabs.sendRequest(tabId, {reqtype: "clickhide-deactivate"}) 595 tab.sendMessage({type: "clickhide-deactivate"});
733 if(changeInfo.status == "loading") 596 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 }); 597 });
751 598
752 setTimeout(function() 599 setTimeout(function()
753 { 600 {
754 var notificationToShow = Notification.getNextToShow(); 601 var notificationToShow = Notification.getNextToShow();
755 if (notificationToShow) 602 if (notificationToShow)
756 showNotification(notificationToShow); 603 showNotification(notificationToShow);
757 }, 3 * 60 * 1000); 604 }, 3 * 60 * 1000);
OLDNEW
« no previous file with comments | « no previous file | block.js » ('j') | safari/common.js » ('J')

Powered by Google App Engine
This is Rietveld