|
| 1 | +/******************************************************************************* |
| 2 | +
|
| 3 | + uBlock Origin - a comprehensive, efficient content blocker |
| 4 | + Copyright (C) 2026-present Raymond Hill |
| 5 | +
|
| 6 | + This program is free software: you can redistribute it and/or modify |
| 7 | + it under the terms of the GNU General Public License as published by |
| 8 | + the Free Software Foundation, either version 3 of the License, or |
| 9 | + (at your option) any later version. |
| 10 | +
|
| 11 | + This program is distributed in the hope that it will be useful, |
| 12 | + but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 13 | + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 14 | + GNU General Public License for more details. |
| 15 | +
|
| 16 | + You should have received a copy of the GNU General Public License |
| 17 | + along with this program. If not, see {http://www.gnu.org/licenses/}. |
| 18 | +
|
| 19 | + Home: https://github.com/gorhill/uBlock |
| 20 | +
|
| 21 | +*/ |
| 22 | + |
| 23 | +import { registerScriptlet } from './base.js'; |
| 24 | +import { safeSelf } from './safe-self.js'; |
| 25 | + |
| 26 | +/** |
| 27 | + * @scriptlet prevent-navigation |
| 28 | + * |
| 29 | + * @description |
| 30 | + * Conditionally abort navigation events. |
| 31 | + * |
| 32 | + * @param [pattern] |
| 33 | + * Optional. A pattern to match against the assigned value. The pattern can be |
| 34 | + * a plain string, or a regex. Prepend with `!` to reverse the match condition. |
| 35 | + * No pattern |
| 36 | + * |
| 37 | + * Reference: |
| 38 | + * https://github.com/AdguardTeam/Scriptlets/commit/cd2d8eefd5 |
| 39 | + * */ |
| 40 | + |
| 41 | +export function preventNavigation( |
| 42 | + pattern = '' |
| 43 | +) { |
| 44 | + const safe = safeSelf(); |
| 45 | + const logPrefix = safe.makeLogPrefix('prevent-navigation', pattern); |
| 46 | + const needle = pattern === 'location.href' ? self.location.href : pattern; |
| 47 | + const matcher = safe.initPattern(needle, { canNegate: true }); |
| 48 | + self.navigation.addEventListener('navigate', ev => { |
| 49 | + if ( ev.userInitiated ) { return; } |
| 50 | + const { url } = ev.destination; |
| 51 | + if ( pattern === '' ) { |
| 52 | + safe.uboLog(logPrefix, `Navigation to ${url}`); |
| 53 | + return; |
| 54 | + } |
| 55 | + if ( safe.testPattern(matcher, url) ) { |
| 56 | + ev.preventDefault(); |
| 57 | + safe.uboLog(logPrefix, `Prevented navigation to ${url}`); |
| 58 | + } |
| 59 | + }); |
| 60 | +} |
| 61 | +registerScriptlet(preventNavigation, { |
| 62 | + name: 'prevent-navigation.js', |
| 63 | + dependencies: [ |
| 64 | + safeSelf, |
| 65 | + ], |
| 66 | + world: 'ISOLATED', |
| 67 | +}); |
0 commit comments