Skip to content

Commit

Permalink
Use parseMatchArg helper
Browse files Browse the repository at this point in the history
Use native startsWith in parseMatchArg helper
Return string in parseMatchArg helper
Add test with cookie value
Set isInvertedMatchCookie and isInvertedMatchLocalStorage to false instead of null
Rever test for abort-on-stack-trace
Fix typo in description
  • Loading branch information
AdamWr committed Mar 27, 2023
1 parent df78bc3 commit eaf048a
Show file tree
Hide file tree
Showing 5 changed files with 78 additions and 43 deletions.
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Added

- ability to click element if `cookie`/`localStorage` item doesn't exist in `trusted-click-element` scriptlet [#298](https://github.com/AdguardTeam/Scriptlets/issues/298)
- ability for `trusted-click-element` scriptlet to click element if `cookie`/`localStorage` item doesn't exist [#298](https://github.com/AdguardTeam/Scriptlets/issues/298)
- static delay between multiple clicks in `trusted-click-element` [#284](https://github.com/AdguardTeam/Scriptlets/issues/284)

### Fixed
Expand Down
5 changes: 3 additions & 2 deletions src/helpers/string-utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -238,10 +238,11 @@ export const isValidMatchNumber = (match) => {
*/
export const parseMatchArg = (match) => {
const INVERT_MARKER = '!';
const isInvertedMatch = startsWith(match, INVERT_MARKER);
// In case if "match" is "undefined" return "false"
const isInvertedMatch = match ? match.startsWith(INVERT_MARKER) : false;
const matchValue = isInvertedMatch ? match.slice(1) : match;
const matchRegexp = toRegExp(matchValue);
return { isInvertedMatch, matchRegexp };
return { isInvertedMatch, matchRegexp, matchValue };
};

/**
Expand Down
31 changes: 15 additions & 16 deletions src/scriptlets/trusted-click-element.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
parseCookieString,
throttle,
logMessage,
parseMatchArg,
} from '../helpers/index';

/* eslint-disable max-len */
Expand Down Expand Up @@ -67,7 +68,7 @@ import {
* example.com#%#//scriptlet('trusted-click-element', 'button[name="agree"]', '!cookie:cmpconsent')
* ```
*
* 9. Click element only if specified cookie string and localStorage item do not exist
* 9. Click element only if specified cookie string and localStorage item does not exist
* ```
* example.com#%#//scriptlet('trusted-click-element', 'button[name="agree"]', '!cookie:cmpconsent, !localStorage:promo')
* ```
Expand All @@ -85,7 +86,6 @@ export function trustedClickElement(source, selectors, extraMatch = '', delay =
const LOCAL_STORAGE_MATCH_MARKER = 'localStorage:';
const SELECTORS_DELIMITER = ',';
const COOKIE_STRING_DELIMITER = ';';
const INVERT_MARKER = '!';
// Regex to split match pairs by commas, avoiding the ones included in regexes
const EXTRA_MATCH_DELIMITER = /(,\s*){1}(?=!?cookie:|!?localStorage:)/;

Expand All @@ -107,8 +107,8 @@ export function trustedClickElement(source, selectors, extraMatch = '', delay =

const cookieMatches = [];
const localStorageMatches = [];
let isInvertedMatchCookie = null;
let isInvertedMatchLocalStorage = null;
let isInvertedMatchCookie = false;
let isInvertedMatchLocalStorage = false;

if (extraMatch) {
// Get all match marker:value pairs from argument
Expand All @@ -119,18 +119,16 @@ export function trustedClickElement(source, selectors, extraMatch = '', delay =
// Filter match pairs by marker
parsedExtraMatch.forEach((matchStr) => {
if (matchStr.indexOf(COOKIE_MATCH_MARKER) > -1) {
isInvertedMatchCookie = !!matchStr.startsWith(INVERT_MARKER);
if (isInvertedMatchCookie) {
matchStr = matchStr.slice(1);
}
const { isInvertedMatch, matchValue } = parseMatchArg(matchStr);
isInvertedMatchCookie = isInvertedMatch;
matchStr = matchValue;
const cookieMatch = matchStr.replace(COOKIE_MATCH_MARKER, '');
cookieMatches.push(cookieMatch);
}
if (matchStr.indexOf(LOCAL_STORAGE_MATCH_MARKER) > -1) {
isInvertedMatchLocalStorage = !!matchStr.startsWith(INVERT_MARKER);
if (isInvertedMatchLocalStorage) {
matchStr = matchStr.slice(1);
}
const { isInvertedMatch, matchValue } = parseMatchArg(matchStr);
isInvertedMatchLocalStorage = isInvertedMatch;
matchStr = matchValue;
const localStorageMatch = matchStr.replace(LOCAL_STORAGE_MATCH_MARKER, '');
localStorageMatches.push(localStorageMatch);
}
Expand Down Expand Up @@ -167,8 +165,8 @@ export function trustedClickElement(source, selectors, extraMatch = '', delay =
});
});

const shouldClick = cookiesMatched !== isInvertedMatchCookie;
if (!shouldClick) {
const shouldRun = cookiesMatched !== isInvertedMatchCookie;
if (!shouldRun) {
return;
}
}
Expand All @@ -180,8 +178,8 @@ export function trustedClickElement(source, selectors, extraMatch = '', delay =
return itemValue || itemValue === '';
});

const shouldClick = localStorageMatched !== isInvertedMatchLocalStorage;
if (!shouldClick) {
const shouldRun = localStorageMatched !== isInvertedMatchLocalStorage;
if (!shouldRun) {
return;
}
}
Expand Down Expand Up @@ -312,4 +310,5 @@ trustedClickElement.injections = [
parseCookieString,
throttle,
logMessage,
parseMatchArg,
];
27 changes: 3 additions & 24 deletions tests/scriptlets/abort-on-stack-trace.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -330,36 +330,15 @@ test('abort String.fromCharCode, inline script', (assert) => {
assert.strictEqual(window.hit, 'FIRED', 'hit fired');
});

// TODO: check why this test fails
// test('do NOT abort Math.round, test for injected script', (assert) => {
// const property = 'Math.round';
// const stackMatch = 'injectedScript';
// const scriptletArgs = [property, stackMatch];
// runScriptlet(name, scriptletArgs);

// let testPassed = false;
// try {
// const testNumber = Math.round(1.5);
// // eslint-disable-next-line no-console
// console.log('Number:', testNumber);
// testPassed = true;
// } catch (error) {
// // eslint-disable-next-line no-console
// console.log('Something went wrong', error);
// }
// assert.strictEqual(testPassed, true, 'testPassed set to true, script has not been aborted');
// assert.strictEqual(window.hit, undefined, 'hit should NOT fire');
// });

test('do NOT abort Math.sqrt, test for injected script', (assert) => {
const property = 'Math.sqrt';
test('do NOT abort Math.round, test for injected script', (assert) => {
const property = 'Math.round';
const stackMatch = 'injectedScript';
const scriptletArgs = [property, stackMatch];
runScriptlet(name, scriptletArgs);

let testPassed = false;
try {
const testNumber = Math.sqrt(4);
const testNumber = Math.round(1.5);
// eslint-disable-next-line no-console
console.log('Number:', testNumber);
testPassed = true;
Expand Down
56 changes: 56 additions & 0 deletions tests/scriptlets/trusted-click-element.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -430,6 +430,34 @@ test('extraMatch - single cookie revert, click', (assert) => {
}, 150);
});

test('extraMatch - single cookie with value revert match, should click', (assert) => {
const cookieKey = 'clickValue';
const cookieVal = 'true';
const cookieData = concatCookieNameValuePath(cookieKey, cookieVal, '/');
document.cookie = cookieData;
const EXTRA_MATCH_STR = `!cookie:${cookieKey}=false`;

const ELEM_COUNT = 1;
// Check elements for being clicked and hit func execution
const ASSERTIONS = ELEM_COUNT + 1;
assert.expect(ASSERTIONS);
const done = assert.async();

const selectorsString = `#${PANEL_ID} > #${CLICKABLE_NAME}${ELEM_COUNT}`;

runScriptlet(name, [selectorsString, EXTRA_MATCH_STR]);
const panel = createPanel();
const clickable = createClickable(1);
panel.appendChild(clickable);

setTimeout(() => {
assert.ok(clickable.getAttribute('clicked'), 'Element should be clicked');
assert.strictEqual(window.hit, 'FIRED', 'hit func executed');
clearCookie(cookieKey);
done();
}, 150);
});

test('extraMatch - single cookie revert match, should not click', (assert) => {
const cookieKey = 'doNotClick';
const cookieData = concatCookieNameValuePath(cookieKey, 'true', '/');
Expand Down Expand Up @@ -457,6 +485,34 @@ test('extraMatch - single cookie revert match, should not click', (assert) => {
}, 150);
});

test('extraMatch - single cookie with value revert match, should not click', (assert) => {
const cookieKey = 'doNotClickValue';
const cookieVal = 'true';
const cookieData = concatCookieNameValuePath(cookieKey, cookieVal, '/');
document.cookie = cookieData;
const EXTRA_MATCH_STR = `!cookie:${cookieKey}=${cookieVal}`;

const ELEM_COUNT = 1;
// Check elements for being clicked and hit func execution
const ASSERTIONS = ELEM_COUNT + 1;
assert.expect(ASSERTIONS);
const done = assert.async();

const selectorsString = `#${PANEL_ID} > #${CLICKABLE_NAME}${ELEM_COUNT}`;

runScriptlet(name, [selectorsString, EXTRA_MATCH_STR]);
const panel = createPanel();
const clickable = createClickable(1);
panel.appendChild(clickable);

setTimeout(() => {
assert.notOk(clickable.getAttribute('clicked'), 'Element should not be clicked');
assert.strictEqual(window.hit, undefined, 'hit should not fire');
clearCookie(cookieKey);
done();
}, 150);
});

test('extraMatch - single localStorage revert, click', (assert) => {
const itemName = 'revertItem';
const EXTRA_MATCH_STR = `!localStorage:${itemName}`;
Expand Down

0 comments on commit eaf048a

Please sign in to comment.