Revert "Merge pull request #3303 from brave/cosmetic-filtering-frontend"

This reverts commit fe9f891260, reversing
changes made to 4e6ba95fbb.

Was causing problems specifically on Linux because of the Rust dependency.
This should fix https://github.com/brave/brave-browser/issues/7055
This will un-fix https://github.com/brave/brave-browser/issues/5381
This commit is contained in:
Brian Clifton
2019-12-18 09:33:13 -07:00
parent 950778a7a1
commit 756285ccb0
36 changed files with 13 additions and 807 deletions
+1 -1
View File
@@ -1,7 +1,7 @@
use_relative_paths = True
deps = {
"vendor/adblock_rust_ffi": "https://github.com/brave/adblock-rust-ffi.git@d757c647699ff7e6dacc5d7bbd51649b509609a5",
"vendor/adblock_rust_ffi": "https://github.com/brave/adblock-rust-ffi.git@89127a30655eaf54cf73794309846084ea8b91b9",
"vendor/autoplay-whitelist": "https://github.com/brave/autoplay-whitelist.git@ea527a4d36051daedb34421e129c98eda06cb5d3",
"vendor/extension-whitelist": "https://github.com/brave/extension-whitelist.git@7843f62e26a23c51336330e220e9d7992680aae9",
"vendor/hashset-cpp": "https://github.com/brave/hashset-cpp.git@6eab0271d014ff09bd9f38abe1e0c117e13e9aa9",
-2
View File
@@ -68,9 +68,7 @@ source_set("extensions") {
"//brave/components/brave_component_updater/browser",
"//brave/components/brave_extension:generated_resources",
"//brave/components/brave_extension:static_resources",
"//brave/components/brave_shields/browser",
"//chrome/browser/extensions",
"//chrome/common",
"//components/gcm_driver:gcm_driver",
"//components/gcm_driver:gcm_buildflags",
"//components/prefs",
@@ -10,12 +10,10 @@
#include <utility>
#include "base/strings/string_number_conversions.h"
#include "brave/browser/brave_browser_process_impl.h"
#include "brave/browser/extensions/api/brave_action_api.h"
#include "brave/browser/webcompat_reporter/webcompat_reporter_dialog.h"
#include "brave/common/extensions/api/brave_shields.h"
#include "brave/common/extensions/extension_constants.h"
#include "brave/components/brave_shields/browser/ad_block_service.h"
#include "brave/components/brave_shields/browser/brave_shields_p3a.h"
#include "brave/components/brave_shields/browser/brave_shields_util.h"
#include "brave/components/brave_shields/browser/brave_shields_web_contents_observer.h"
@@ -25,7 +23,6 @@
#include "chrome/browser/extensions/chrome_extension_function_details.h"
#include "chrome/browser/extensions/extension_tab_util.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/chrome_features.h"
#include "content/public/browser/web_contents.h"
#include "extensions/browser/extension_util.h"
@@ -44,40 +41,6 @@ const char kInvalidControlTypeError[] = "Invalid ControlType.";
} // namespace
ExtensionFunction::ResponseAction
BraveShieldsHostnameCosmeticResourcesFunction::Run() {
std::unique_ptr<brave_shields::HostnameCosmeticResources::Params> params(
brave_shields::HostnameCosmeticResources::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get());
base::Optional<base::Value> resources = g_brave_browser_process->
ad_block_service()->HostnameCosmeticResources(params->hostname);
if (!resources || !resources->is_dict()) {
return RespondNow(Error(
"Hostname-specific cosmetic resources could not be returned"));
}
auto result_list = std::make_unique<base::ListValue>();
result_list->GetList().push_back(std::move(*resources));
return RespondNow(ArgumentList(std::move(result_list)));
}
ExtensionFunction::ResponseAction BraveShieldsClassIdStylesheetFunction::Run() {
std::unique_ptr<brave_shields::ClassIdStylesheet::Params> params(
brave_shields::ClassIdStylesheet::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get());
std::string stylesheet = g_brave_browser_process->
ad_block_service()->ClassIdStylesheet(params->classes,
params->ids,
params->exceptions);
return RespondNow(OneArgument(std::make_unique<base::Value>(stylesheet)));
}
ExtensionFunction::ResponseAction BraveShieldsAllowScriptsOnceFunction::Run() {
std::unique_ptr<brave_shields::AllowScriptsOnce::Params> params(
brave_shields::AllowScriptsOnce::Params::Create(*args_));
@@ -154,14 +117,6 @@ BraveShieldsGetBraveShieldsEnabledFunction::Run() {
return RespondNow(OneArgument(std::move(result)));
}
ExtensionFunction::ResponseAction
BraveShieldsGetCosmeticFilteringEnabledFunction::Run() {
auto result = std::make_unique<base::Value>(
base::FeatureList::IsEnabled(features::kBraveAdblockCosmeticFiltering));
return RespondNow(OneArgument(std::move(result)));
}
ExtensionFunction::ResponseAction BraveShieldsSetAdControlTypeFunction::Run() {
std::unique_ptr<brave_shields::SetAdControlType::Params> params(
brave_shields::SetAdControlType::Params::Create(*args_));
@@ -11,26 +11,6 @@
namespace extensions {
namespace api {
class BraveShieldsHostnameCosmeticResourcesFunction : public ExtensionFunction {
public:
DECLARE_EXTENSION_FUNCTION("braveShields.hostnameCosmeticResources", UNKNOWN)
protected:
~BraveShieldsHostnameCosmeticResourcesFunction() override {}
ResponseAction Run() override;
};
class BraveShieldsClassIdStylesheetFunction : public ExtensionFunction {
public:
DECLARE_EXTENSION_FUNCTION("braveShields.classIdStylesheet", UNKNOWN)
protected:
~BraveShieldsClassIdStylesheetFunction() override {}
ResponseAction Run() override;
};
class BraveShieldsAllowScriptsOnceFunction : public ExtensionFunction {
public:
DECLARE_EXTENSION_FUNCTION("braveShields.allowScriptsOnce", UNKNOWN)
@@ -72,18 +52,6 @@ class BraveShieldsGetBraveShieldsEnabledFunction : public ExtensionFunction {
ResponseAction Run() override;
};
class BraveShieldsGetCosmeticFilteringEnabledFunction
: public ExtensionFunction {
public:
DECLARE_EXTENSION_FUNCTION("braveShields.getCosmeticFilteringEnabled",
UNKNOWN)
protected:
~BraveShieldsGetCosmeticFilteringEnabledFunction() override {}
ResponseAction Run() override;
};
class BraveShieldsSetAdControlTypeFunction : public ExtensionFunction {
public:
DECLARE_EXTENSION_FUNCTION("braveShields.setAdControlType", UNKNOWN)
@@ -3,12 +3,6 @@
* 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/. */
#define BRAVE_FEATURE_ENTRIES \
{"brave-adblock-cosmetic-filtering", \
flag_descriptions::kBraveAdblockCosmeticFilteringName, \
flag_descriptions::kBraveAdblockCosmeticFilteringDescription, kOsAll, \
FEATURE_VALUE_TYPE(features::kBraveAdblockCosmeticFiltering)},
#define SetFeatureEntryEnabled SetFeatureEntryEnabled_ChromiumImpl
#include "../../../../chrome/browser/about_flags.cc" // NOLINT
#include "../../../../components/flags_ui/flags_state.cc" // NOLINT
@@ -1,12 +0,0 @@
/* Copyright (c) 2019 The Brave Authors. All rights reserved.
* 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/. */
#include "../../../../chrome/browser/flag_descriptions.cc"
namespace flag_descriptions {
const char kBraveAdblockCosmeticFilteringName[] = "Enable cosmetic filtering";
const char kBraveAdblockCosmeticFilteringDescription[] =
"Enable support for cosmetic filtering";
}
@@ -1,16 +0,0 @@
/* Copyright (c) 2019 The Brave Authors. All rights reserved.
* 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/. */
#ifndef BRAVE_CHROMIUM_SRC_CHROME_BROWSER_FLAG_DESCRIPTIONS_H_
#define BRAVE_CHROMIUM_SRC_CHROME_BROWSER_FLAG_DESCRIPTIONS_H_
#include "../../../../chrome/browser/flag_descriptions.h"
namespace flag_descriptions {
extern const char kBraveAdblockCosmeticFilteringName[];
extern const char kBraveAdblockCosmeticFilteringDescription[];
}
#endif // BRAVE_CHROMIUM_SRC_CHROME_BROWSER_FLAG_DESCRIPTIONS_H_
@@ -1,12 +0,0 @@
/* Copyright (c) 2019 The Brave Authors. All rights reserved.
* 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/. */
#include "../../../../chrome/common/chrome_features.cc"
namespace features {
const base::Feature kBraveAdblockCosmeticFiltering{
"BraveAdblockCosmeticFiltering",
base::FEATURE_DISABLED_BY_DEFAULT};
}
@@ -1,16 +0,0 @@
/* Copyright (c) 2019 The Brave Authors. All rights reserved.
* 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/. */
#ifndef BRAVE_CHROMIUM_SRC_CHROME_COMMON_CHROME_FEATURES_H_
#define BRAVE_CHROMIUM_SRC_CHROME_COMMON_CHROME_FEATURES_H_
#include "../../../../chrome/common/chrome_features.h"
namespace features {
COMPONENT_EXPORT(CHROME_FEATURES)
extern const base::Feature kBraveAdblockCosmeticFiltering;
}
#endif // BRAVE_CHROMIUM_SRC_CHROME_COMMON_CHROME_FEATURES_H_
-76
View File
@@ -73,65 +73,6 @@
"description": "Notifies the browser about the fact of showing the panel",
"parameters": []
},
{
"name": "hostnameCosmeticResources",
"type": "function",
"description": "Get a cosmetic adblocking stylesheet, generic style exceptions, and script injections specific for the given hostname and domain",
"parameters": [
{
"name": "hostname",
"type": "string"
},
{
"type": "function",
"name": "callback",
"parameters": [
{
"name": "hostnameSpecificResources",
"type": "object",
"properties": {
"hide_selectors": {"type": "array", "items": {"type": "string"}, "description": "Hostname-specific CSS selectors that should be hidden from the page"},
"style_selectors": {"type": "object", "additionalProperties": {"type": "array", "items": {"type": "string"}}, "description": "Hostname-specific CSS selectors that should be restyled, with their associated CSS style rules"},
"exceptions": {"type": "array", "items": {"type": "string"}, "description": "Hostname-specific overrides for generic cosmetic blocking selectors"},
"injected_script": {"type": "string", "description": "A script to inject as the page is loading"}
}
}
]
}
]
},
{
"name": "classIdStylesheet",
"type": "function",
"description": "Get a stylesheet of generic rules that may apply to the given set of classes and ids without any of the given excepted selectors",
"parameters": [
{
"name": "classes",
"type": "array",
"items": {"type": "string"}
},
{
"name": "ids",
"type": "array",
"items": {"type": "string"}
},
{
"name": "exceptions",
"type": "array",
"items": {"type": "string"}
},
{
"type": "function",
"name": "callback",
"parameters": [
{
"name": "stylesheet",
"type": "string"
}
]
}
]
},
{
"name": "getBraveShieldsEnabled",
"type": "function",
@@ -153,23 +94,6 @@
}
]
},
{
"name": "getCosmeticFilteringEnabled",
"type": "function",
"description": "Get whether or not the cosmetic filtering feature flag is enabled",
"parameters": [
{
"type": "function",
"name": "callback",
"parameters": [
{
"name": "enabled",
"type": "boolean"
}
]
}
]
},
{
"name": "setAdControlType",
"type": "function",
@@ -9,7 +9,6 @@ transpile_web_ui("brave_extension") {
["brave_extension_background", rebase_path("background.ts")],
["content", rebase_path("content.ts")],
["content_dapps", rebase_path("content_dapps.ts")],
["content_cosmetic", rebase_path("content_cosmetic.ts")],
["webstore", rebase_path("webstore.ts")],
]
@@ -137,28 +137,3 @@ export const shieldsReady: actions.ShieldsReady = () => {
type: types.SHIELDS_READY
}
}
export const generateClassIdStylesheet = (tabId: number, classes: string[], ids: string[]) => {
return {
type: types.GENERATE_CLASS_ID_STYLESHEET,
tabId,
classes,
ids
}
}
export const cosmeticFilterRuleExceptions = (tabId: number, exceptions: string[]) => {
return {
type: types.COSMETIC_FILTER_RULE_EXCEPTIONS,
tabId,
exceptions
}
}
export const contentScriptsLoaded: actions.ContentScriptsLoaded = (tabId: number, url: string) => {
return {
type: types.CONTENT_SCRIPTS_LOADED,
tabId,
url
}
}
@@ -2,34 +2,6 @@
* 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/. */
import shieldsPanelActions from '../actions/shieldsPanelActions'
const generateCosmeticBlockingStylesheet = (hideSelectors: string[], styleSelectors: any) => {
let stylesheet = ''
if (hideSelectors.length > 0) {
stylesheet += hideSelectors[0]
for (const selector of hideSelectors.slice(1)) {
stylesheet += ',' + selector
}
stylesheet += '{display:none !important;}\n'
}
for (const selector in styleSelectors) {
stylesheet += selector + '{' + styleSelectors[selector] + '\n'
}
return stylesheet
}
export const injectClassIdStylesheet = (tabId: number, classes: string[], ids: string[], exceptions: string[]) => {
chrome.braveShields.classIdStylesheet(classes, ids, exceptions, stylesheet => {
chrome.tabs.insertCSS(tabId, {
code: stylesheet,
cssOrigin: 'user',
runAt: 'document_start'
})
})
}
export const addSiteCosmeticFilter = async (origin: string, cssfilter: string) => {
chrome.storage.local.get('cosmeticFilterList', (storeData = {}) => {
let storeList = Object.assign({}, storeData.cosmeticFilterList)
@@ -50,34 +22,7 @@ export const removeSiteFilter = (origin: string) => {
})
}
export const applyAdblockCosmeticFilters = (tabId: number, hostname: string) => {
chrome.braveShields.hostnameCosmeticResources(hostname, async (resources) => {
if (chrome.runtime.lastError) {
console.warn('Unable to get cosmetic filter data for the current host')
return
}
const stylesheet = generateCosmeticBlockingStylesheet(resources.hide_selectors, resources.style_selectors)
if (stylesheet) {
chrome.tabs.insertCSS(tabId, {
code: stylesheet,
cssOrigin: 'user',
runAt: 'document_start'
})
}
if (resources.injected_script) {
chrome.tabs.executeScript(tabId, {
code: resources.injected_script,
runAt: 'document_start'
})
}
shieldsPanelActions.cosmeticFilterRuleExceptions(tabId, resources.exceptions)
})
}
export const applyCSSCosmeticFilters = (tabId: number, hostname: string) => {
export const applySiteFilters = (tabId: number, hostname: string) => {
chrome.storage.local.get('cosmeticFilterList', (storeData = {}) => {
if (!storeData.cosmeticFilterList) {
if (process.env.NODE_ENV === 'shields_development') {
@@ -27,8 +27,7 @@ export const getShieldSettingsForTabData = (tabData?: chrome.tabs.Tab) => {
chrome.braveShields.getHTTPSEverywhereEnabledAsync(tabData.url),
chrome.braveShields.getNoScriptControlTypeAsync(tabData.url),
chrome.braveShields.getFingerprintingControlTypeAsync(tabData.url),
chrome.braveShields.getCookieControlTypeAsync(tabData.url),
chrome.braveShields.getCosmeticFilteringEnabledAsync()
chrome.braveShields.getCookieControlTypeAsync(tabData.url)
]).then((details) => {
return {
url: url.href,
@@ -41,8 +40,7 @@ export const getShieldSettingsForTabData = (tabData?: chrome.tabs.Tab) => {
httpUpgradableResources: details[2] ? 'block' : 'allow',
javascript: details[3],
fingerprinting: details[4],
cookies: details[5],
cosmeticBlocking: details[6]
cookies: details[5]
}
}).catch(() => {
return {
@@ -51,7 +49,6 @@ export const getShieldSettingsForTabData = (tabData?: chrome.tabs.Tab) => {
hostname,
id: tabData.id,
braveShields: 'block',
cosmeticBlocking: 0,
ads: 0,
trackers: 0,
httpUpgradableResources: 0,
@@ -4,7 +4,6 @@ import {
removeSiteFilter,
removeAllFilters
} from '../api/cosmeticFilterAPI'
import shieldsPanelActions from '../actions/shieldsPanelActions'
export let rule = {
host: '',
@@ -50,33 +49,6 @@ chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
rule.host = msg.baseURI
break
}
case 'classIdStylesheet': {
const tab = sender.tab
if (tab === undefined) {
break
}
const tabId = tab.id
if (tabId === undefined) {
break
}
shieldsPanelActions.generateClassIdStylesheet(tabId, msg.classes, msg.ids)
break
}
case 'contentScriptsLoaded': {
const tab = sender.tab
if (tab === undefined) {
break
}
const tabId = tab.id
if (tabId === undefined) {
break
}
const url = tab.url
if (url === undefined) {
break
}
shieldsPanelActions.contentScriptsLoaded(tabId, url)
}
}
})
@@ -33,11 +33,7 @@ import {
reportBrokenSite
} from '../api/shieldsAPI'
import { reloadTab } from '../api/tabsAPI'
import {
injectClassIdStylesheet,
applyAdblockCosmeticFilters,
applyCSSCosmeticFilters
} from '../api/cosmeticFilterAPI'
import { applySiteFilters } from '../api/cosmeticFilterAPI'
// Helpers
import { getAllowedScriptsOrigins } from '../../helpers/noScriptUtils'
@@ -62,7 +58,7 @@ export default function shieldsPanelReducer (
state = shieldsPanelState.resetBlockingResources(state, action.tabId)
state = noScriptState.resetNoScriptInfo(state, action.tabId, new window.URL(action.url).origin)
}
applyCSSCosmeticFilters(action.tabId, getHostname(action.url))
applySiteFilters(action.tabId, getHostname(action.url))
break
}
case windowTypes.WINDOW_REMOVED: {
@@ -109,9 +105,6 @@ export default function shieldsPanelReducer (
case shieldsPanelTypes.SHIELDS_PANEL_DATA_UPDATED: {
state = shieldsPanelState.updateTabShieldsData(state, action.details.id, action.details)
shieldsPanelState.updateShieldsIcon(state)
if (chrome.test && shieldsPanelState.getActiveTabData(state)) {
chrome.test.sendMessage('brave-extension-shields-data-ready')
}
break
}
case shieldsPanelTypes.SHIELDS_TOGGLED: {
@@ -347,47 +340,6 @@ export default function shieldsPanelReducer (
})
break
}
case shieldsPanelTypes.GENERATE_CLASS_ID_STYLESHEET: {
const tabData = state.tabs[action.tabId]
if (!tabData) {
console.error('Active tab not found')
break
}
const exceptions = tabData.cosmeticFilters.ruleExceptions
// setTimeout is used to prevent injectClassIdStylesheet from calling
// another Redux function immediately
setTimeout(() => injectClassIdStylesheet(action.tabId, action.classes, action.ids, exceptions), 0)
break
}
case shieldsPanelTypes.COSMETIC_FILTER_RULE_EXCEPTIONS: {
const tabData = state.tabs[action.tabId]
if (!tabData) {
console.error('Active tab not found')
break
}
state = shieldsPanelState.saveCosmeticFilterRuleExceptions(state, action.tabId, action.exceptions)
chrome.tabs.sendMessage(action.tabId, {
type: 'cosmeticFilterGenericExceptions'
})
break
}
case shieldsPanelTypes.CONTENT_SCRIPTS_LOADED: {
const tabData = state.tabs[action.tabId]
if (!tabData) {
console.error('Active tab not found')
break
}
const cosmeticBlockingEnabled = tabData.cosmeticBlocking
chrome.braveShields.getBraveShieldsEnabledAsync(action.url)
.then((braveShieldsEnabled: boolean) => {
const doCosmeticBlocking = braveShieldsEnabled && cosmeticBlockingEnabled
if (doCosmeticBlocking) {
applyAdblockCosmeticFilters(action.tabId, getHostname(action.url))
}
})
break
}
}
if (!areObjectsEqual(state.persistentData, initialPersistentData)) {
@@ -20,6 +20,3 @@ export const SET_FINAL_SCRIPTS_BLOCKED_ONCE_STATE = 'SET_FINAL_SCRIPTS_BLOCKED_O
export const SET_ADVANCED_VIEW_FIRST_ACCESS = 'SET_ADVANCED_VIEW_FIRST_ACCESS'
export const TOGGLE_ADVANCED_VIEW = 'TOGGLE_ADVANCED_VIEW'
export const SHIELDS_READY = 'SHIELDS_READY'
export const GENERATE_CLASS_ID_STYLESHEET = 'GENERATE_CLASS_ID_STYLESHEET'
export const COSMETIC_FILTER_RULE_EXCEPTIONS = 'COSMETIC_FILTER_RULE_EXCEPTIONS'
export const CONTENT_SCRIPTS_LOADED = 'CONTENT_SCRIPTS_LOADED'
@@ -1,13 +1,3 @@
// Notify the background script as soon as the content script has loaded.
// chrome.tabs.insertCSS may sometimes fail to inject CSS in a newly navigated
// page when using the chrome.webNavigation API.
// See: https://bugs.chromium.org/p/chromium/issues/detail?id=331654#c15
// The RenderView should always be ready when the content script begins, so
// this message is used to trigger CSS insertion instead.
chrome.runtime.sendMessage({
type: 'contentScriptsLoaded'
})
const unique = require('unique-selector').default
let target: EventTarget | null
@@ -30,7 +20,6 @@ chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
switch (action) {
case 'getTargetSelector': {
sendResponse(unique(target))
break
}
}
})
@@ -1,80 +0,0 @@
const queriedIds = new Set()
const queriedClasses = new Set()
const regexWhitespace = /\s/
const getClassesAndIds = function (addedNodes: Element[]) {
const ids = []
const classes = []
for (const node of addedNodes) {
let nodeId = node.id
if (nodeId && nodeId.length !== 0) {
nodeId = nodeId.trim()
if (!queriedIds.has(nodeId) && nodeId.length !== 0) {
ids.push(nodeId)
queriedIds.add(nodeId)
}
}
let nodeClass = node.className
if (nodeClass && nodeClass.length !== 0 && !regexWhitespace.test(nodeClass)) {
if (!queriedClasses.has(nodeClass)) {
classes.push(nodeClass)
queriedClasses.add(nodeClass)
}
} else {
let nodeClasses = node.classList
if (nodeClasses) {
let j = nodeClasses.length
while (j--) {
const nodeClassJ = nodeClasses[j]
if (queriedClasses.has(nodeClassJ) === false) {
classes.push(nodeClassJ)
queriedClasses.add(nodeClassJ)
}
}
}
}
}
return { classes, ids }
}
const handleNewNodes = (newNodes: Element[]) => {
const { classes, ids } = getClassesAndIds(newNodes)
chrome.runtime.sendMessage({
type: 'classIdStylesheet',
classes,
ids
})
}
function applyCosmeticFilterMutationObserver () {
let targetNode = document.documentElement
let observer = new MutationObserver(mutations => {
const nodeList: Element[] = []
for (const mutation of mutations) {
for (let nodeIndex = 0; nodeIndex < mutation.addedNodes.length; nodeIndex++) {
nodeList.push(mutation.addedNodes[nodeIndex] as Element)
}
}
handleNewNodes(nodeList)
})
let observerConfig = {
childList: true,
subtree: true
}
observer.observe(targetNode, observerConfig)
}
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
const action = typeof msg === 'string' ? msg : msg.type
switch (action) {
case 'cosmeticFilterGenericExceptions': {
let allNodes = Array.from(document.querySelectorAll('[id],[class]'))
handleNewNodes(allNodes)
applyCosmeticFilterMutationObserver()
sendResponse(null)
break
}
}
})
@@ -28,8 +28,7 @@
"https://*/*"
],
"js": [
"out/content.bundle.js",
"out/content_cosmetic.bundle.js"
"out/content.bundle.js"
],
"run_at": "document_start",
"all_frames": true
@@ -112,12 +112,6 @@ export const updateResourceBlocked: shieldState.UpdateResourceBlocked = (state,
return { ...state, tabs }
}
export const saveCosmeticFilterRuleExceptions: shieldState.SaveCosmeticFilterRuleExceptions = (state, tabId, exceptions) => {
const tabs: shieldState.Tabs = { ...state.tabs }
tabs[tabId] = { ...tabs[tabId], ...{ cosmeticFilters: { ...tabs[tabId].cosmeticFilters, ruleExceptions: exceptions } } }
return { ...state, tabs }
}
export const resetBlockingStats: shieldState.ResetBlockingStats = (state, tabId) => {
const tabs: shieldState.Tabs = { ...state.tabs }
tabs[tabId] = { ...tabs[tabId], ...{ adsBlocked: 0, trackersBlocked: 0, httpsRedirected: 0, javascriptBlocked: 0, fingerprintingBlocked: 0 } }
@@ -7,7 +7,6 @@ import { BlockTypes, BlockOptions, BlockFPOptions, BlockJSOptions, BlockCookiesO
export interface ShieldDetails {
id: number
cosmeticBlocking: boolean
ads: BlockOptions
trackers: BlockOptions
httpUpgradableResources: BlockOptions
@@ -173,37 +172,6 @@ export interface ShieldsReady {
(): ShieldsReadyReturn
}
interface GenerateClassIdStylesheetReturn {
type: types.GENERATE_CLASS_ID_STYLESHEET,
tabId: number,
classes: string[],
ids: string[]
}
export interface GenerateClassIdStylesheet {
(tabId: number, classes: string[], ids: string[]): GenerateClassIdStylesheetReturn
}
interface CosmeticFilterRuleExceptionsReturn {
type: types.COSMETIC_FILTER_RULE_EXCEPTIONS,
tabId: number,
exceptions: string[]
}
export interface CosmeticFilterRuleExceptions {
(tabId: number, exceptions: string[]): CosmeticFilterRuleExceptionsReturn
}
interface ContentScriptsLoadedReturn {
type: types.CONTENT_SCRIPTS_LOADED,
tabId: number,
url: string,
}
export interface ContentScriptsLoaded {
(tabId: number, url: string): ContentScriptsLoadedReturn
}
export type shieldPanelActions =
ShieldsPanelDataUpdatedReturn |
ShieldsToggledReturn |
@@ -221,7 +189,4 @@ export type shieldPanelActions =
SetAllScriptsBlockedCurrentStateReturn |
SetFinalScriptsBlockedStateReturn |
SetAdvancedViewFirstAccessReturn |
ShieldsReadyReturn |
GenerateClassIdStylesheetReturn |
CosmeticFilterRuleExceptionsReturn |
ContentScriptsLoadedReturn
ShieldsReadyReturn
@@ -6,7 +6,3 @@ export type BlockTypes = 'ads' | 'trackers' | 'httpUpgradableResources' | 'javas
export type BlockOptions = 'allow' | 'block'
export type BlockFPOptions = 'allow' | 'block' | 'block_third_party'
export type BlockCookiesOptions = 'allow' | 'block' | 'block_third_party'
export interface CosmeticFilteringState {
ruleExceptions: Array<string>
}
@@ -22,6 +22,3 @@ export type SET_FINAL_SCRIPTS_BLOCKED_ONCE_STATE = typeof types.SET_FINAL_SCRIPT
export type SET_ADVANCED_VIEW_FIRST_ACCESS = typeof types.SET_ADVANCED_VIEW_FIRST_ACCESS
export type TOGGLE_ADVANCED_VIEW = typeof types.TOGGLE_ADVANCED_VIEW
export type SHIELDS_READY = typeof types.SHIELDS_READY
export type GENERATE_CLASS_ID_STYLESHEET = typeof types.GENERATE_CLASS_ID_STYLESHEET
export type COSMETIC_FILTER_RULE_EXCEPTIONS = typeof types.COSMETIC_FILTER_RULE_EXCEPTIONS
export type CONTENT_SCRIPTS_LOADED = typeof types.CONTENT_SCRIPTS_LOADED
@@ -3,11 +3,9 @@
* You can obtain one at http://mozilla.org/MPL/2.0/. */
import { BlockOptions, BlockTypes, BlockFPOptions, BlockCookiesOptions } from '../other/blockTypes'
import { CosmeticFilteringState } from '../adblock/adblockTypes'
import { NoScriptInfo } from '../other/noScriptInfo'
export interface Tab {
cosmeticBlocking: boolean
ads: BlockOptions
adsBlocked: number
controlsOpen: boolean
@@ -30,7 +28,6 @@ export interface Tab {
trackersBlockedResources: Array<string>
httpsRedirectedResources: Array<string>
fingerprintingBlockedResources: Array<string>
cosmeticFilters: CosmeticFilteringState
}
export interface Tabs {
@@ -88,10 +85,6 @@ export interface UpdateResourceBlocked {
(state: State, tabId: number, blockType: BlockTypes, subresource: string): State
}
export interface SaveCosmeticFilterRuleExceptions {
(state: State, tabId: number, exceptions: Array<string>): State
}
export interface ResetBlockingStats {
(state: State, tabId: number): State
}
@@ -55,7 +55,6 @@ source_set("browser") {
}
deps = [
"//base",
"//brave/components/brave_component_updater/browser",
"//brave/components/content_settings/core/browser",
"//brave/content:common",
@@ -12,7 +12,6 @@
#include "base/bind.h"
#include "base/files/file_path.h"
#include "base/json/json_reader.h"
#include "base/macros.h"
#include "base/memory/ptr_util.h"
#include "base/strings/utf_string_conversions.h"
@@ -196,19 +195,6 @@ bool AdBlockBaseService::TagExists(const std::string& tag) {
return std::find(tags_.begin(), tags_.end(), tag) != tags_.end();
}
base::Optional<base::Value> AdBlockBaseService::HostnameCosmeticResources(
const std::string& hostname) {
return base::JSONReader::Read(
this->ad_block_client_->hostnameCosmeticResources(hostname));
}
std::string AdBlockBaseService::ClassIdStylesheet(
const std::vector<std::string>& classes,
const std::vector<std::string>& ids,
const std::vector<std::string>& exceptions) {
return this->ad_block_client_->classIdStylesheet(classes, ids, exceptions);
}
void AdBlockBaseService::GetDATFileData(const base::FilePath& dat_file_path) {
base::PostTaskAndReplyWithResult(
FROM_HERE, {base::ThreadPool(), base::MayBlock()},
@@ -16,7 +16,6 @@
#include "base/files/file_path.h"
#include "base/memory/weak_ptr.h"
#include "base/sequence_checker.h"
#include "base/values.h"
#include "brave/components/brave_shields/browser/base_brave_shields_service.h"
#include "brave/components/brave_component_updater/browser/dat_file_util.h"
#include "content/public/common/resource_type.h"
@@ -47,13 +46,6 @@ class AdBlockBaseService : public BaseBraveShieldsService {
void EnableTag(const std::string& tag, bool enabled);
bool TagExists(const std::string& tag);
base::Optional<base::Value> HostnameCosmeticResources(
const std::string& hostname);
std::string ClassIdStylesheet(
const std::vector<std::string>& classes,
const std::vector<std::string>& ids,
const std::vector<std::string>& exceptions);
protected:
friend class ::AdBlockServiceTest;
bool Init() override;
@@ -19,13 +19,11 @@
#include "brave/vendor/adblock_rust_ffi/src/wrapper.hpp"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_features.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/prefs/pref_service.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/test/browser_test_utils.h"
#include "extensions/test/extension_test_message_listener.h"
#include "net/dns/mock_host_resolver.h"
using content::BrowserThread;
@@ -220,15 +218,6 @@ class AdBlockServiceTest : public ExtensionBrowserTest {
base::CreateSingleThreadTaskRunner({BrowserThread::IO}).get()));
ASSERT_TRUE(io_helper->Run());
}
void WaitForBraveExtensionShieldsDataReady() {
// Sometimes, the page can start loading before the Shields panel has
// received information about the window and tab it's loaded in.
ExtensionTestMessageListener extension_listener(
"brave-extension-shields-data-ready",
false);
ASSERT_TRUE(extension_listener.WaitUntilSatisfied());
}
};
// Load a page with an ad image, and make sure it is blocked.
@@ -785,172 +774,3 @@ IN_PROC_BROWSER_TEST_F(AdBlockServiceTest, RedirectRulesAreRespected) {
EXPECT_TRUE(as_expected);
EXPECT_EQ(browser()->profile()->GetPrefs()->GetUint64(kAdsBlocked), 1ULL);
}
class CosmeticFilteringEnabledTest : public AdBlockServiceTest {
public:
CosmeticFilteringEnabledTest() {
feature_list_.InitAndEnableFeature(
features::kBraveAdblockCosmeticFiltering);
}
private:
base::test::ScopedFeatureList feature_list_;
};
// Ensure no cosmetic filtering occurs when the feature flag has not been
// enabled
IN_PROC_BROWSER_TEST_F(AdBlockServiceTest, CosmeticFilteringSimple) {
UpdateAdBlockInstanceWithRules(
"b.com###ad-banner\n"
"##.ad");
WaitForBraveExtensionShieldsDataReady();
GURL tab_url = embedded_test_server()->GetURL("b.com",
"/cosmetic_filtering.html");
ui_test_utils::NavigateToURL(browser(), tab_url);
content::WebContents* contents =
browser()->tab_strip_model()->GetActiveWebContents();
bool as_expected = false;
ASSERT_TRUE(ExecuteScriptAndExtractBool(
contents,
"checkSelector('#ad-banner', 'display', 'block')",
&as_expected));
EXPECT_TRUE(as_expected);
as_expected = false;
ASSERT_TRUE(ExecuteScriptAndExtractBool(
contents,
"checkSelector('.ad-banner', 'display', 'block')",
&as_expected));
EXPECT_TRUE(as_expected);
as_expected = false;
ASSERT_TRUE(ExecuteScriptAndExtractBool(
contents,
"checkSelector('.ad', 'display', 'block')",
&as_expected));
EXPECT_TRUE(as_expected);
}
// Test simple cosmetic filtering
IN_PROC_BROWSER_TEST_F(CosmeticFilteringEnabledTest, CosmeticFilteringSimple) {
UpdateAdBlockInstanceWithRules(
"b.com###ad-banner\n"
"##.ad");
WaitForBraveExtensionShieldsDataReady();
GURL tab_url = embedded_test_server()->GetURL("b.com",
"/cosmetic_filtering.html");
ui_test_utils::NavigateToURL(browser(), tab_url);
content::WebContents* contents =
browser()->tab_strip_model()->GetActiveWebContents();
bool as_expected = false;
ASSERT_TRUE(ExecuteScriptAndExtractBool(
contents,
"checkSelector('#ad-banner', 'display', 'none')",
&as_expected));
EXPECT_TRUE(as_expected);
as_expected = false;
ASSERT_TRUE(ExecuteScriptAndExtractBool(
contents,
"checkSelector('.ad-banner', 'display', 'block')",
&as_expected));
EXPECT_TRUE(as_expected);
as_expected = false;
ASSERT_TRUE(ExecuteScriptAndExtractBool(
contents,
"checkSelector('.ad', 'display', 'none')",
&as_expected));
EXPECT_TRUE(as_expected);
}
// Test cosmetic filtering on elements added dynamically
IN_PROC_BROWSER_TEST_F(CosmeticFilteringEnabledTest, CosmeticFilteringDynamic) {
UpdateAdBlockInstanceWithRules("##.blockme");
WaitForBraveExtensionShieldsDataReady();
GURL tab_url = embedded_test_server()->GetURL("b.com",
"/cosmetic_filtering.html");
ui_test_utils::NavigateToURL(browser(), tab_url);
content::WebContents* contents =
browser()->tab_strip_model()->GetActiveWebContents();
bool as_expected = false;
ASSERT_TRUE(ExecuteScriptAndExtractBool(
contents,
"addElementsDynamically();\n"
"checkSelector('.blockme', 'display', 'none')",
&as_expected));
EXPECT_TRUE(as_expected);
as_expected = false;
ASSERT_TRUE(ExecuteScriptAndExtractBool(
contents,
"checkSelector('.dontblockme', 'display', 'block')",
&as_expected));
EXPECT_TRUE(as_expected);
}
// Test custom style rules
IN_PROC_BROWSER_TEST_F(CosmeticFilteringEnabledTest,
CosmeticFilteringCustomStyle) {
UpdateAdBlockInstanceWithRules("b.com##.ad:style(padding-bottom: 10px)");
WaitForBraveExtensionShieldsDataReady();
GURL tab_url = embedded_test_server()->GetURL("b.com",
"/cosmetic_filtering.html");
ui_test_utils::NavigateToURL(browser(), tab_url);
content::WebContents* contents =
browser()->tab_strip_model()->GetActiveWebContents();
bool as_expected = false;
ASSERT_TRUE(ExecuteScriptAndExtractBool(
contents,
"checkSelector('.ad', 'padding-bottom', '10px')",
&as_expected));
EXPECT_TRUE(as_expected);
}
// Test rules overridden by hostname-specific exception rules
IN_PROC_BROWSER_TEST_F(CosmeticFilteringEnabledTest, CosmeticFilteringUnhide) {
UpdateAdBlockInstanceWithRules(
"##.ad\n"
"b.com#@#.ad\n"
"###ad-banner\n"
"a.com#@##ad-banner");
WaitForBraveExtensionShieldsDataReady();
GURL tab_url = embedded_test_server()->GetURL("b.com",
"/cosmetic_filtering.html");
ui_test_utils::NavigateToURL(browser(), tab_url);
content::WebContents* contents =
browser()->tab_strip_model()->GetActiveWebContents();
bool as_expected = false;
ASSERT_TRUE(ExecuteScriptAndExtractBool(
contents,
"checkSelector('.ad', 'display', 'block')",
&as_expected));
EXPECT_TRUE(as_expected);
as_expected = false;
ASSERT_TRUE(ExecuteScriptAndExtractBool(
contents,
"checkSelector('#ad-banner', 'display', 'none')",
&as_expected));
EXPECT_TRUE(as_expected);
}
-10
View File
@@ -203,7 +203,6 @@ declare namespace chrome.braveShields {
const allowScriptsOnce: any
const setBraveShieldsEnabledAsync: any
const getBraveShieldsEnabledAsync: any
const getCosmeticFilteringEnabledAsync: any
const setAdControlTypeAsync: any
const getAdControlTypeAsync: any
const setCookieControlTypeAsync: any
@@ -217,15 +216,6 @@ declare namespace chrome.braveShields {
const onShieldsPanelShown: any
const reportBrokenSite: any
interface HostnameSpecificResources {
hide_selectors: string[]
style_selectors: any
exceptions: string[]
injected_script: string
}
const hostnameCosmeticResources: (hostname: string, callback: (resources: HostnameSpecificResources) => void) => void
const classIdStylesheet: (classes: string[], ids: string[], exceptions: string[], callback: (stylesheet: string) => void) => void
type BraveShieldsViewPreferences = {
showAdvancedView: boolean
}
@@ -177,7 +177,7 @@ describe('cosmeticFilter API', () => {
})
})
})
describe('applyCSSCosmeticFilters', () => {
describe('applySiteFilters', () => {
const filter = '#cssFilter'
const filter2 = '#cssFilter2'
@@ -206,7 +206,7 @@ describe('cosmeticFilter API', () => {
'brave.com': [filter]
}
})
cosmeticFilterAPI.applyCSSCosmeticFilters(1, 'brave.com')
cosmeticFilterAPI.applySiteFilters(1, 'brave.com')
expect(insertCSSStub.getCall(0).args[0]).toEqual(1)
expect(insertCSSStub.getCall(0).args[1]).toEqual({
code: `${filter} {display: none !important;}`,
@@ -220,7 +220,7 @@ describe('cosmeticFilter API', () => {
'brave.com': [filter, filter2]
}
})
cosmeticFilterAPI.applyCSSCosmeticFilters(1, 'brave.com')
cosmeticFilterAPI.applySiteFilters(1, 'brave.com')
expect(insertCSSStub.getCall(0).args[0]).toEqual(1)
expect(insertCSSStub.getCall(0).args[1]).toEqual({
code: `${filter } {display: none !important;}`,
@@ -239,7 +239,7 @@ describe('cosmeticFilter API', () => {
getStorageStub.yields({
cosmeticFilterList: {}
})
cosmeticFilterAPI.applyCSSCosmeticFilters(1, 'brave.com')
cosmeticFilterAPI.applySiteFilters(1, 'brave.com')
expect(insertCSSStub.called).toBe(false)
})
it('doesn\'t apply filters if storage is explicitly undefined', () => {
@@ -248,7 +248,7 @@ describe('cosmeticFilter API', () => {
'brave.com': undefined
}
})
cosmeticFilterAPI.applyCSSCosmeticFilters(1, 'brave.com')
cosmeticFilterAPI.applySiteFilters(1, 'brave.com')
expect(insertCSSStub.called).toBe(false)
})
})
@@ -38,7 +38,6 @@ describe('Shields API', () => {
origin: 'https://www.brave.com',
hostname: 'www.brave.com',
braveShields: 'block',
cosmeticBlocking: true,
ads: 'block',
trackers: 'block',
httpUpgradableResources: 'block',
@@ -95,7 +94,6 @@ describe('Shields API', () => {
})
it('resolves and calls requestShieldPanelData', (cb) => {
const details: ShieldDetails = {
cosmeticBlocking: true,
ads: 'block',
trackers: 'block',
httpUpgradableResources: 'block',
-3
View File
@@ -217,9 +217,6 @@ export const getMockChrome = () => {
getBraveShieldsEnabledAsync: function (url: string) {
return Promise.resolve(false)
},
getCosmeticFilteringEnabledAsync: function (url: string) {
return Promise.resolve(true)
},
getAdControlTypeAsync: function (url: string) {
return Promise.resolve('block')
},
@@ -21,11 +21,3 @@ index 0ab55be2f96853137cec8928621360e9f639b467..34e01378c8e413af12399bc3ca30188b
const FeatureEntry::Choice kPassiveListenersChoices[] = {
{flags_ui::kGenericExperimentChoiceDefault, "", ""},
@@ -4688,6 +4688,7 @@ const FeatureEntry kFeatureEntries[] = {
// "LoginCustomFlags" in tools/metrics/histograms/enums.xml. See "Flag
// Histograms" in tools/metrics/histograms/README.md (run the
// AboutFlagsHistogramTest unit test to verify this process).
+ BRAVE_FEATURE_ENTRIES
};
class FlagsStateSingleton {
-41
View File
@@ -1,41 +0,0 @@
<html>
<head>
<script>
function addElementsDynamically() {
let root = document.documentElement;
for (let i = 0; i < 10; i++) {
const e = document.createElement('div')
e.className = 'blockme'
root.appendChild(e);
}
for (let i = 0; i < 10; i++) {
const e = document.createElement('div')
e.className = 'dontblockme'
root.appendChild(e);
}
}
function checkSelector(selector, property, expected) {
setTimeout(() => {
let elements = [].slice.call(document.querySelectorAll(selector));
let result = elements.every(e => {
let style = window.getComputedStyle(e);
return style[property] === expected;
})
window.domAutomationController.send(result)
}, 1500)
}
</script>
</head>
<body>
<div id="ad-banner"></div>
<div class="ad-banner">
<div class="ad"></div>
</div>
<div class="ad"></div>
<div class="ad"></div>
</body>
</html>