├── src ├── inject_everywhere.css ├── options │ ├── maps_embed.mjs │ ├── framepermission.html │ ├── options.html │ ├── framepermission.js │ ├── options.css │ └── options.mjs ├── inject_main.js ├── popup │ ├── popup.css │ ├── popup.html │ └── popup.js ├── pref.js ├── inject_frame.js ├── permission.js ├── inject_frame_permission.js ├── prefmaker.mjs ├── Scrollability.js ├── inject_everywhere.js ├── background.js └── ScrollableMap.js ├── .github ├── FUNDING.yml └── workflows │ ├── test.yml │ └── codeql-analysis.yml ├── images ├── maps_16.png ├── maps_48.png ├── maps_128.png └── permission_icon.png ├── .gitignore ├── test ├── unit │ ├── fakes.js │ ├── Scrollability_test.js │ └── permission_test.js ├── auto │ ├── maplibre_traveler_map.mjs │ ├── hey_whats_that.mjs │ ├── google_com_travel.mjs │ ├── embedded_maps.mjs │ ├── google_com_maps.mjs │ └── options_page.mjs ├── multimap-test.html ├── chrome_browser_action.js ├── manual │ └── manual_test.js └── mapdriver.js ├── .npmrc ├── manifest_chrome_template.json ├── manifest_template.json ├── package.json ├── README.md ├── gulputils.mjs ├── privacy.md ├── LICENSE └── gulpfile.mjs /src/inject_everywhere.css: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: mauricelam 2 | -------------------------------------------------------------------------------- /images/maps_16.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mauricelam/ScrollMaps/HEAD/images/maps_16.png -------------------------------------------------------------------------------- /images/maps_48.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mauricelam/ScrollMaps/HEAD/images/maps_48.png -------------------------------------------------------------------------------- /images/maps_128.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mauricelam/ScrollMaps/HEAD/images/maps_128.png -------------------------------------------------------------------------------- /images/permission_icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mauricelam/ScrollMaps/HEAD/images/permission_icon.png -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | gen/ 3 | node_modules/ 4 | scrollmaps.sublime-workspace 5 | src/options/maps_embed_with_key.mjs 6 | -------------------------------------------------------------------------------- /test/unit/fakes.js: -------------------------------------------------------------------------------- 1 | chrome = { 2 | runtime: { 3 | getManifest() { 4 | return { 5 | version: 10000 6 | } 7 | } 8 | } 9 | }; -------------------------------------------------------------------------------- /.npmrc: -------------------------------------------------------------------------------- 1 | ;;;; 2 | ; npm userconfig file 3 | ; this is a simple ini-formatted file 4 | ; lines that start with semi-colons are comments. 5 | ; read `npm help config` for help on the various options 6 | ;;;; 7 | -------------------------------------------------------------------------------- /src/options/maps_embed.mjs: -------------------------------------------------------------------------------- 1 | // This URL needs to be overridden to include an API key. 2 | export const SCROLLMAPS_IFRAME_URL = `https://www.google.com/maps/embed/v1/view?zoom=12¢er=37.3861%2C-122.0839`; -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Run Unit Tests 2 | 3 | on: 4 | push: 5 | branches: [ chrome ] 6 | pull_request: 7 | branches: [ chrome ] 8 | 9 | jobs: 10 | test: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: actions/checkout@v3 14 | - name: Set up Node.js 15 | uses: actions/setup-node@v3 16 | with: 17 | node-version: '18' # Or a version compatible with your project 18 | - name: Install dependencies 19 | run: npm install 20 | - name: Run unit tests 21 | run: gulp unit 22 | -------------------------------------------------------------------------------- /src/inject_main.js: -------------------------------------------------------------------------------- 1 | // Code injected into the "MAIN" execution world. (See chrome.scripting.ExecutionWorld) 2 | 3 | if (window.SM_INJECT_MAIN === undefined) { 4 | window.SM_INJECT_MAIN = true; 5 | 6 | const origSetPointerCapture = Element.prototype.setPointerCapture; 7 | Element.prototype.setPointerCapture = function (pointerId) { 8 | if (pointerId !== 10088) { 9 | origSetPointerCapture.apply(this, arguments); 10 | } 11 | }; 12 | 13 | const origReleasePointerCapture = Element.prototype.releasePointerCapture; 14 | Element.prototype.releasePointerCapture = function (pointerId) { 15 | if (pointerId !== 10088) { 16 | origReleasePointerCapture.apply(this, arguments); 17 | } 18 | }; 19 | } 20 | -------------------------------------------------------------------------------- /src/options/framepermission.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ScrollMaps options 5 | 6 | 7 | 8 |
9 | 14 |
15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /src/popup/popup.css: -------------------------------------------------------------------------------- 1 | body { background-color: whiteSmoke; font-family: Helvetica, Trebuchet MS, Arial, sans-serif; font-size: 14px; } 2 | 3 | #box { 4 | background: linear-gradient(top, #DDD 0%, #EAEAEA 1% ); 5 | border: 1px solid #BBB; 6 | margin: auto; 7 | position: relative; 8 | width: 300px; 9 | border-radius: 5px; 10 | box-sizing: border-box; 11 | } 12 | .box-content { padding: 15px; padding-top: 4px; } 13 | 14 | .button_bar { 15 | text-align: right; 16 | padding: 4px; 17 | } 18 | 19 | .button_bar > a { 20 | font-size: 12px; 21 | text-decoration: none; 22 | } 23 | 24 | .button_bar > a:hover { 25 | opacity: 0.8; 26 | } 27 | 28 | .disable-options .PMcheckbox { display: none; } 29 | 30 | .PMcheckbox { margin: 7px 0px; display: flex; vertical-align: middle; } 31 | .PMcheckbox input { margin-right: 10px; } 32 | .PMcheckbox label { vertical-align: middle; display: inline-block; } 33 | 34 | label.disabled { opacity: 0.3; } 35 | .PMcheckbox_labeltext { margin: 2px 0px; } 36 | .PMcheckbox_smalltext { color: #666; font-size: 12px; } 37 | 38 | .hidden { display: none; } 39 | -------------------------------------------------------------------------------- /manifest_chrome_template.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ScrollMaps", 3 | "version": null, 4 | "manifest_version": 3, 5 | "minimum_chrome_version": "93", 6 | "description": "Allow you to use two finger scroll on your Mac trackpad in online maps.", 7 | "background": { 8 | "service_worker": "background.min.js" 9 | }, 10 | "web_accessible_resources": [{ 11 | "resources": ["images/permission_icon.png"], 12 | "matches": [""] 13 | }], 14 | "content_security_policy": { 15 | "extension_pages": "script-src 'self'; object-src 'self'" 16 | }, 17 | "options_ui": { 18 | "page": "src/options/options.html", 19 | "open_in_tab": true 20 | }, 21 | "icons": { 22 | "16": "images/maps_16.png", 23 | "48": "images/maps_48.png", 24 | "128": "images/maps_128.png" 25 | }, 26 | "action": {}, 27 | "permissions": [ 28 | "storage", 29 | "scripting", 30 | "activeTab" 31 | ], 32 | "host_permissions": [ 33 | "*://maps.google.com/", 34 | "*://www.google.com/maps/", 35 | "<%= all_google_maps_urls %>" 36 | ], 37 | "optional_host_permissions": [ 38 | "" 39 | ] 40 | } 41 | -------------------------------------------------------------------------------- /manifest_template.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ScrollMaps", 3 | "version": null, 4 | "manifest_version": 3, 5 | "minimum_chrome_version": "93", 6 | "description": "Allow you to use two finger scroll on your Mac trackpad in online maps.", 7 | "browser_specific_settings": { 8 | "gecko": { 9 | "id": "{c0dd22ca-492e-4bcf-ab68-53c6633892fe}", 10 | "strict_min_version": "109.0" 11 | } 12 | }, 13 | "background": { 14 | "scripts": ["background.min.js"] 15 | }, 16 | "web_accessible_resources": [{ 17 | "resources": ["images/permission_icon.png"], 18 | "matches": [""] 19 | }], 20 | "content_security_policy": { 21 | "extension_pages": "script-src 'self'; object-src 'self'" 22 | }, 23 | "options_ui": { 24 | "page": "src/options/options.html", 25 | "open_in_tab": true 26 | }, 27 | "icons": { 28 | "16": "images/maps_16.png", 29 | "48": "images/maps_48.png", 30 | "128": "images/maps_128.png" 31 | }, 32 | "action": {}, 33 | "permissions": [ 34 | "storage", 35 | "scripting", 36 | "activeTab" 37 | ], 38 | "host_permissions": [ 39 | "*://maps.google.com/", 40 | "*://www.google.com/maps/", 41 | "<%= all_google_maps_urls %>" 42 | ], 43 | "optional_permissions": [ 44 | "" 45 | ] 46 | } 47 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "scrollmaps", 3 | "version": "5.1.0", 4 | "description": "Allow you to use two finger scroll on your Mac trackpad in online maps", 5 | "main": "ScrollableMap.js", 6 | "scripts": { 7 | "postversion": "gulp postVersion" 8 | }, 9 | "repository": { 10 | "type": "git", 11 | "url": "git+https://github.com/mauricelam/ScrollMaps.git" 12 | }, 13 | "author": "Maurice Lam", 14 | "license": "Apache-2.0", 15 | "bugs": { 16 | "url": "https://github.com/mauricelam/ScrollMaps/issues" 17 | }, 18 | "homepage": "https://github.com/mauricelam/ScrollMaps", 19 | "devDependencies": { 20 | "async-done": "^2.0.0", 21 | "chai": "^4.3.7", 22 | "chromedriver": "^143.0.1", 23 | "del": "^7.0.0", 24 | "geckodriver": "^4.3.1", 25 | "gulp": "^5.0.0", 26 | "gulp-concat": "^2.6.1", 27 | "gulp-mocha": "^9.0.0", 28 | "gulp-newer": "^1.4.0", 29 | "gulp-rename": "^2.0.0", 30 | "gulp-uglify": "^3.0.2", 31 | "gulp-zip": "^5.1.0", 32 | "karma": "^6.4.2", 33 | "karma-chai": "^0.1.0", 34 | "karma-chrome-launcher": "^3.2.0", 35 | "karma-mocha": "^2.0.1", 36 | "minimist": "^1.2.8", 37 | "mocha": "^10.2.0", 38 | "ms-chromium-edge-driver": "^0.5.1", 39 | "open": "^9.1.0", 40 | "selenium-webdriver": "^4.22.0" 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/options/options.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ScrollMaps options 5 | 6 | 7 | 8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 | 16 |

ScrollMaps extension need additional permission to work in this embedded Google Maps

17 |
18 |
19 |
20 |
21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /src/options/framepermission.js: -------------------------------------------------------------------------------- 1 | // Workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=1392624, which allows the background 2 | // page to create a new tab to ask the user for permission, because we cannot directly do that in 3 | // neither the content script nor the background script. 4 | // 5 | // Used only on Firefox. 6 | 7 | function getRequestingTabId() { 8 | const url = new URL(location.href); 9 | return parseInt(url.searchParams.get('id'), 10); 10 | } 11 | 12 | function init() { 13 | const permissonBtn = document.getElementById('frame-perm-btn'); 14 | const boxContent = document.getElementById('box-content'); 15 | chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { 16 | if (message.action === 'waitForPermission') { 17 | console.log('waiting for permission', sender, sendResponse); 18 | permissonBtn.onclick = async () => { 19 | let granted = await Permission.requestFramePermission(); 20 | if (granted) { 21 | sendResponse(granted); 22 | window.close(); 23 | } 24 | }; 25 | boxContent.style.visibility = 'visible'; 26 | responseSender = sendResponse; 27 | return true; 28 | } 29 | }); 30 | } 31 | 32 | document.addEventListener('DOMContentLoaded', init, false); 33 | -------------------------------------------------------------------------------- /test/unit/Scrollability_test.js: -------------------------------------------------------------------------------- 1 | describe('Scrollability tests', function() { 2 | 3 | it('isScrollable null element', () => { 4 | assert.isFalse(Scrollability.isScrollable(null)); 5 | }); 6 | 7 | it('isScrollable elem', () => { 8 | const elem = document.createElement('div'); 9 | assert.isFalse(Scrollability.isScrollable(elem)); 10 | }); 11 | 12 | const elem = document.createElement('div'); 13 | elem.style.overflow = 'scroll'; 14 | elem.style.width = '50px'; 15 | elem.style.height = '50px'; 16 | const child = document.createElement('div') 17 | child.style.width = '100px'; 18 | child.style.height = '100px'; 19 | document.body.appendChild(elem) 20 | elem.appendChild(child) 21 | 22 | it('isScrollable elem', () => { 23 | assert.isTrue(Scrollability.isScrollable(elem)); 24 | assert.isFalse(Scrollability.isScrollable(child)); 25 | }); 26 | 27 | it('hasScrollableParent', () => { 28 | assert.isTrue(Scrollability.hasScrollableParent(elem)); 29 | assert.isTrue(Scrollability.hasScrollableParent(child)); 30 | assert.isFalse(Scrollability.hasScrollableParent(document.documentElement)); 31 | }); 32 | 33 | it('hasScrollableParent fixed position', () => { 34 | child.style.position = 'fixed'; 35 | assert.isFalse(Scrollability.hasScrollableParent(child)); 36 | }); 37 | }); -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ScrollMaps 2 | Lets you scroll with two fingers on your trackpad within online maps 3 | 4 | - [Chrome web store link](https://chrome.google.com/webstore/detail/scrollmaps/jifommjndpnefcfplgnbhabocomgdjjg) 5 | - [Firefox Add-ons store link](https://addons.mozilla.org/en-US/firefox/addon/scrollmaps) 6 | - [Microsoft Edge addon link](https://microsoftedge.microsoft.com/addons/detail/scrollmaps/mdhhlgkmnlaiofbbemcmigjleiiefmga) 7 | 8 | ## Supported map providers 9 | 10 | - Google Maps 11 | - MapBox 12 | - Esri ArcGIS 13 | - Apple MapKit JS 14 | - OpenStreetMap 15 | - and a few others 16 | 17 | ## Building 18 | 19 | After checking out the source, initialize the dependencies using `npm install`. 20 | 21 | After making changes, build a development version using `gulp --`. This will create an unpacked extension under `gen/plugin-10000-` that can then be loaded into Chrome as an unpacked extension. 22 | 23 | You can also use `gulp watch --` to watch for changes and build new dev versions automatically. 24 | 25 | To build the current release version for all browsers, use `gulp release`. 26 | 27 | ## Unit testing 28 | 29 | Unit tests can be run using `gulp unit` or `gulp watchunit`. 30 | 31 | ## Integration Testing 32 | 33 | Tests can be run using `gulp test --`. 34 | 35 | Individual test fails can be run using `mocha` directly: 36 | 37 | ```sh 38 | BROWSER=chrome npx mocha test/auto/google_com_travel.js 39 | ``` 40 | -------------------------------------------------------------------------------- /gulputils.mjs: -------------------------------------------------------------------------------- 1 | import gulp from 'gulp'; 2 | const { series, parallel } = gulp; 3 | import { Transform } from 'stream'; 4 | import asyncDone from 'async-done'; 5 | import child_process from 'child_process'; 6 | 7 | export function makePromise(obj) { 8 | if (obj.then instanceof Function) { 9 | return obj; // Already a then-able, just return 10 | } 11 | return new Promise((resolve, reject) => { 12 | asyncDone(obj, (err, result) => { 13 | err ? reject(err) : resolve(result) 14 | }) 15 | }); 16 | } 17 | 18 | export function runParallel(...tasks) { 19 | return makePromise(parallel(...tasks)); 20 | } 21 | 22 | export function runSeries(...tasks) { 23 | return makePromise(series(...tasks)); 24 | } 25 | 26 | export function execTask(command, options = {}) { 27 | const task = async () => 28 | new Promise((resolve, reject) => { 29 | child_process.exec(command, options, (err, stdout, stderr) => { 30 | if (stdout) console.log(`${command}: ${stdout.trim()}`); 31 | if (stderr) console.warn(`${command}: ${stderr.trim()}`); 32 | err ? reject(err) : resolve(stdout); 33 | }); 34 | }); 35 | task.displayName = `Exec \`${command}\``; 36 | return task; 37 | } 38 | 39 | export function contentTransform(fn) { 40 | return new Transform({ 41 | objectMode: true, 42 | transform(file, enc, cb) { 43 | file.contents = Buffer.from(fn(file.contents, file, enc)); 44 | cb(null, file); 45 | } 46 | }); 47 | } 48 | -------------------------------------------------------------------------------- /test/unit/permission_test.js: -------------------------------------------------------------------------------- 1 | const assert = chai.assert; 2 | 3 | describe('Permission tests', function() { 4 | 5 | const isMapsSite_trueTests = [ 6 | 'https://www.google.com/maps', 7 | 'https://www.google.com/maps/place/1600+Amphitheatre+Pkwy,+Mountain+View,+CA+94043/', 8 | 'http://www.google.com/maps', 9 | 'https://www.google.com.hk/maps', 10 | 'https://www.google.co.uk/maps', 11 | 'https://maps.google.com/', 12 | ]; 13 | for (const site of isMapsSite_trueTests) { 14 | it(`isMapsSite ${site}`, () => { 15 | assert.isTrue(Permission.isMapsSite(site)); 16 | }) 17 | } 18 | 19 | const isMapsSite_falseTests = [ 20 | 'https://www.apple.com/', 21 | 'https://www.google.com.example.com/', 22 | 'https://maps.google.com.example.com/', 23 | 'https://www.google.com/travel', 24 | ]; 25 | for (const site of isMapsSite_falseTests) { 26 | it(`isMapsSite ${site}`, () => { 27 | assert.isFalse(Permission.isMapsSite(site)); 28 | }); 29 | } 30 | 31 | /* global */ chrome = { runtime: { id: 'jifommjndpnefcfplgnbhabocomgdjjg' } }; 32 | it('isOwnExtensionPage options page', () => { 33 | assert.isTrue(Permission.isOwnExtensionPage( 34 | 'chrome-extension://jifommjndpnefcfplgnbhabocomgdjjg/src/options/options.html', 35 | )) 36 | }); 37 | 38 | const isOwnExtensionPage_falseTests = [ 39 | 'chrome-extension://gighmmpiobklfepjocnamgkkbiglidom/options.html#general', // AdBlock options 40 | 'chrome://newtab', 41 | 'chrome://version', 42 | ]; 43 | for (const site of isOwnExtensionPage_falseTests) { 44 | it(`isOwnExtensionPage ${site}`, () => { 45 | assert.isFalse(Permission.isOwnExtensionPage(site)); 46 | }); 47 | } 48 | }); 49 | -------------------------------------------------------------------------------- /src/pref.js: -------------------------------------------------------------------------------- 1 | const PrefManager = { 2 | 3 | _DEFAULTS: { 4 | 'enabled': true, 5 | 'invertScroll': false, 6 | 'invertZoom': false, 7 | 'isolateZoomScroll': true, 8 | 'frameRequireFocus': true, 9 | 'scrollSpeed': 200, 10 | 'zoomSpeed': 250 11 | }, 12 | 13 | getDefault(label) { 14 | return this._DEFAULTS[label]; 15 | }, 16 | 17 | async getOptions() { 18 | return await chrome.storage.local.get(); 19 | }, 20 | 21 | async getAllOptions() { 22 | const options = await this.getOptions(); 23 | return { ...PrefManager._DEFAULTS, ...options }; 24 | }, 25 | 26 | async setOption(key, value) { 27 | await chrome.storage.local.set({ [key]: value }); 28 | }, 29 | 30 | async getOption(key) { 31 | const options = await this.getAllOptions() 32 | return options[key]; 33 | }, 34 | 35 | onPreferenceChanged(key, func) { 36 | chrome.storage.onChanged.addListener((changes, area) => { 37 | if (area === 'local') { 38 | for (const changedKey in changes) { 39 | if (key === null || changedKey === key) { 40 | func(changedKey, changes[changedKey].newValue); 41 | } 42 | } 43 | } 44 | }); 45 | }, 46 | 47 | initBackgroundPage() { 48 | chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { 49 | switch (message.action) { 50 | case 'setPreference': 51 | PrefManager.setOption(message.data.key, message.data.value); 52 | break; 53 | } 54 | }); 55 | } 56 | } 57 | 58 | const Pref = PrefManager; 59 | 60 | async function pref(key) { 61 | return await PrefManager.getOption(key); 62 | } 63 | -------------------------------------------------------------------------------- /privacy.md: -------------------------------------------------------------------------------- 1 | # Privacy Policy 2 | 3 | As required by the add-on store, this is a policy about how this extension handles user data. This is intended to make it easier for users to better understand how the data is handled; for complete understanding, look into the source code for details. 4 | 5 | ## Data sharing and transmission 6 | 7 | All of ScrollMaps runs inside your browser and it does not send data to outside of the extension. The only external components ScrollMaps interacts with is the browser, the page you are using ScrollMaps on, and the map provider like Google Maps. 8 | 9 | ## Data collection and handling 10 | 11 | ScrollMaps functions by listening to scroll events on any supported map canvases and injecting a corresponding event to simulate panning the map. In order to get the available supported map canvases on a given page, ScrollMaps looks through the content on a web page and identifies potential map tiles that are provided by known map providers, like Google Maps, OpenStreetMap, Esri, MapBox, etc. Additionally, ScrollMaps also listens to whether the page is making any web requests to use Maps APIs, in order to determine whether the developer is using the maps canvas. To determine that, ScrollMaps makes use of the URLs of the tab making the request and matches that against the tabs that you currently have open. These URLs are requested from the browser and is never shared outside of the ScrollMaps browser extension, and are erased once you close the browser. 12 | 13 | All of the event capturing described above runs locally on your computer, and the data is not sent back to any servers. 14 | 15 | ## Analytics 16 | 17 | We (ScrollMaps developers) use the statistics provided by the extension store to identify the demographic patterns of our user base. These include data like OS platform, country, and language. These data are gathered by the store, and we do not gather additional data during the usage of the extension. 18 | -------------------------------------------------------------------------------- /src/inject_frame.js: -------------------------------------------------------------------------------- 1 | if (window.SM_FRAME === undefined) { 2 | window.SM_FRAME = { count: 0 }; 3 | SM_FRAME.inframe = (window.top !== window); 4 | 5 | let retries = 3; 6 | 7 | async function injectMaps() { 8 | let elem = document.getElementById('content-container'); 9 | elem = elem || document.querySelector('[role=application]:has(canvas)'); 10 | const minimap = document.getElementById('minimap'); 11 | if (elem || minimap) { 12 | if (elem && !elem.hasAttribute('data-scrollmap')) { 13 | new ScrollableMap(elem, ScrollableMap.TYPE_GOOGLE_MAPS_WEB, SM_FRAME.count++, await Pref.getAllOptions()); 14 | } 15 | if (minimap && !minimap.hasAttribute('data-scrollmap')) { 16 | new ScrollableMap(minimap, ScrollableMap.TYPE_GOOGLE_MAPS_WEB, SM_FRAME.count++, await Pref.getAllOptions()); 17 | } 18 | } 19 | if ((!elem || !minimap) && retries > 0) { 20 | // Retry a few times because the new map canvas is not installed on DOM load 21 | retries--; 22 | setTimeout(injectMaps, 1000); 23 | } 24 | } 25 | 26 | async function injectFrame() { 27 | let elem = document.getElementById('map'); 28 | elem = elem || document.getElementById('mapDiv'); 29 | if (elem) { 30 | new ScrollableMap( 31 | elem, 32 | (SM_FRAME.inframe) ? ScrollableMap.TYPE_GOOGLE_MAPS_IFRAME : ScrollableMap.TYPE_GOOGLE_MAPS_LEGACY, 33 | SM_FRAME.count++, 34 | await Pref.getAllOptions()); 35 | } else if (!SM_FRAME.inframe) { 36 | injectMaps(); 37 | } 38 | } 39 | 40 | if (Permission.isMapsSite(document.URL)) { 41 | if (document.readyState === "complete" 42 | || document.readyState === "loaded" 43 | || document.readyState === "interactive") { 44 | injectFrame(); 45 | } 46 | window.addEventListener('DOMContentLoaded', injectFrame, false); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/options/options.css: -------------------------------------------------------------------------------- 1 | body { background-color: whiteSmoke; font-family: Helvetica, Trebuchet MS, Arial, sans-serif; font-size: 14px; } 2 | 3 | #box { 4 | background: linear-gradient(top, #DDD 0%, #EAEAEA 1% ); 5 | border: 1px solid #BBB; 6 | margin: auto; 7 | margin-top: 50px; 8 | position: relative; 9 | width: 750px; 10 | min-height: 450px; 11 | border-radius: 5px; 12 | box-sizing: border-box; 13 | } 14 | #box-content { padding: 15px; } 15 | #header { font-family: Century Gothic, Arial, sans-serif; user-select: none; cursor: default; 16 | font-size: 30px; margin: auto; color: #333; text-shadow: 0 1px 1px white; 17 | } 18 | 19 | .horizontalLine { border-top: 1px solid #CCC; border-bottom: 1px solid #FFF; margin: 5px 0px; } 20 | .clear { clear: both; } 21 | 22 | #checkboxes { display: inline-block; width: 350px; height: 480px; float: left; position: relative; } 23 | #mapsdemo { width: 100%; height: 100%; } 24 | 25 | #mapsdemo-container { 26 | width: 300px; height: 470px; border: 1px solid #BBB; float: right; 27 | position: relative; 28 | } 29 | 30 | #frame-permission-message { 31 | position: absolute; top: 0px; right: 0px; bottom: 0px; left: 0px; 32 | text-align: center; 33 | background-color: rgba(200, 200, 200, 0.9); 34 | display: none; align-items: center; justify-content: center; flex-direction: column; 35 | } 36 | 37 | #zoomhint { position: absolute; bottom: 3px; right: 5px; font-size: 12px; text-shadow: 0 1px 1px white; color: #888; user-select: none; cursor: default; } 38 | 39 | .PMcheckbox { margin: 7px 0px; white-space: nowrap; vertical-align: middle; } 40 | .PMcheckbox input { margin-right: 10px; } 41 | .PMcheckbox label { vertical-align: middle; display: inline-block; } 42 | 43 | .PMcheckbox_labelwrap { display: inline-block; user-select: none; margin: 5px 0px; } 44 | .PMcheckbox_labeltext { margin: 2px 0px; } 45 | .PMcheckbox_smalltext { color: #666; font-size: 12px; } 46 | 47 | .PMslider { margin: 7px 0px; padding-left: 24px; } 48 | .PMslider label { display: block; margin: 5px 0px; } 49 | .PMslider input { margin: 2px 0px; vertical-align: middle; width: 250px; } 50 | .PMslider .PMsliderPreview { vertical-align: middle; margin-left: 10px; font-size: 12px; color: #666666; } 51 | -------------------------------------------------------------------------------- /.github/workflows/codeql-analysis.yml: -------------------------------------------------------------------------------- 1 | # For most projects, this workflow file will not need changing; you simply need 2 | # to commit it to your repository. 3 | # 4 | # You may wish to alter this file to override the set of languages analyzed, 5 | # or to provide custom queries or build logic. 6 | # 7 | # ******** NOTE ******** 8 | # We have attempted to detect the languages in your repository. Please check 9 | # the `language` matrix defined below to confirm you have the correct set of 10 | # supported CodeQL languages. 11 | # 12 | name: "CodeQL" 13 | 14 | on: 15 | push: 16 | branches: [ chrome ] 17 | pull_request: 18 | # The branches below must be a subset of the branches above 19 | branches: [ chrome ] 20 | schedule: 21 | - cron: '44 18 * * 0' 22 | 23 | jobs: 24 | analyze: 25 | name: Analyze 26 | runs-on: ubuntu-latest 27 | permissions: 28 | actions: read 29 | contents: read 30 | security-events: write 31 | 32 | strategy: 33 | fail-fast: false 34 | matrix: 35 | language: [ 'javascript' ] 36 | # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ] 37 | # Learn more about CodeQL language support at https://git.io/codeql-language-support 38 | 39 | steps: 40 | - name: Checkout repository 41 | uses: actions/checkout@v2 42 | 43 | # Initializes the CodeQL tools for scanning. 44 | - name: Initialize CodeQL 45 | uses: github/codeql-action/init@v1 46 | with: 47 | languages: ${{ matrix.language }} 48 | # If you wish to specify custom queries, you can do so here or in a config file. 49 | # By default, queries listed here will override any specified in a config file. 50 | # Prefix the list here with "+" to use these queries and those in the config file. 51 | # queries: ./path/to/local/query, your-org/your-repo/queries@main 52 | 53 | # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). 54 | # If this step fails, then you should remove it and run the build manually (see below) 55 | - name: Autobuild 56 | uses: github/codeql-action/autobuild@v1 57 | 58 | # ℹ️ Command-line programs to run using the OS shell. 59 | # 📚 https://git.io/JvXDl 60 | 61 | # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines 62 | # and modify them (or add more) to build your code if your project 63 | # uses a compiled language 64 | 65 | #- run: | 66 | # make bootstrap 67 | # make release 68 | 69 | - name: Perform CodeQL Analysis 70 | uses: github/codeql-action/analyze@v1 71 | -------------------------------------------------------------------------------- /test/auto/maplibre_traveler_map.mjs: -------------------------------------------------------------------------------- 1 | import { By } from 'selenium-webdriver'; 2 | import { MapDriver, assertIn, sleep } from '../mapdriver.js'; 3 | 4 | const TEST_TIMEOUT = 10 * 60 * 1000; 5 | 6 | 7 | describe('travelermap test suite', function() { 8 | this.retries(0); 9 | this.slow(TEST_TIMEOUT); 10 | this.timeout(TEST_TIMEOUT); 11 | let driver; 12 | let mapDriver; 13 | 14 | before(async () => { 15 | mapDriver = await MapDriver.create(); 16 | driver = mapDriver.driver; 17 | }); 18 | after(async () => { 19 | await mapDriver.quit(); 20 | }); 21 | 22 | it('https://travelermap.net/parks/usa', async () => { 23 | await driver.get('about:blank'); 24 | await sleep(500); 25 | await driver.get('https://travelermap.net/parks/usa#map=10.2/37.6926/-121.9915'); 26 | await sleep(1000); 27 | 28 | let mapButton = await mapDriver.driver.findElement(By.id("js__traveler-mobile-map-toggle")); 29 | await mapButton.click(); 30 | 31 | let elem = await mapDriver.activateAndWaitForScrollMapsLoaded(); 32 | console.log('checking lat lng 1'); 33 | await assertZoomLatLng([10.2, 0], [37.6926, 0.01], [-121.9915, 0.01]); 34 | 35 | // This scroll is a no-op, since we haven't clicked the map yet 36 | // It wouldn't scroll the page because the event is not trusted 37 | await mapDriver.scroll(elem, 0, -300); 38 | await sleep(2500); 39 | console.log('checking lat lng 2'); 40 | await assertZoomLatLng([10.2, 0], [38.3708, 0.05], [-121.9915, 0.05]); 41 | 42 | await mapDriver.scroll(elem, 300, 300); 43 | await sleep(2500); 44 | console.log('checking lat lng 3'); 45 | await assertZoomLatLng([10.2, 0], [37.585, 0.05], [-120.9879, 0.05]); 46 | 47 | // // Execute zoom action 48 | await mapDriver.pinchGesture(elem, 64); 49 | await sleep(1000); 50 | console.log('checking lat lng after pinch'); 51 | await assertZoomLatLng([7.26, 0], [37.585, 0.05], [-120.9879, 0.05]); 52 | }); 53 | 54 | async function getUrlLatLngZoom() { 55 | const url = await driver.getCurrentUrl(); 56 | const pattern = new RegExp('https://.*#map=(-?[\\d\\.]+)/(-?[\\d\\.]+)/(-?[\\d\\.]+).*'); 57 | const match = pattern.exec(url); 58 | if (!match) return {}; 59 | const [_, zoom, lat, lng] = match.map(Number); 60 | return { lat, lng, zoom }; 61 | } 62 | 63 | async function assertZoomLatLng(expectedZoom, expectedLat, expectedLng) { 64 | const { lat, lng, zoom } = await getUrlLatLngZoom(); 65 | assertIn(zoom, expectedZoom); 66 | assertIn(lat, expectedLat); 67 | assertIn(lng, expectedLng); 68 | } 69 | }); 70 | -------------------------------------------------------------------------------- /test/auto/hey_whats_that.mjs: -------------------------------------------------------------------------------- 1 | import assert from 'assert'; 2 | import { By } from 'selenium-webdriver'; 3 | import { MapDriver, assertIn, sleep } from '../mapdriver.js'; 4 | 5 | const TEST_TIMEOUT = 10 * 60 * 1000; 6 | 7 | 8 | describe('heywhatsthat test suite', function() { 9 | this.retries(1); 10 | this.slow(TEST_TIMEOUT); 11 | this.timeout(TEST_TIMEOUT); 12 | let driver; 13 | let mapDriver; 14 | 15 | before(async () => { 16 | mapDriver = await MapDriver.create(); 17 | driver = mapDriver.driver; 18 | }); 19 | after(async () => { 20 | await mapDriver.quit(); 21 | }); 22 | 23 | it('https://www.heywhatsthat.com/?view=P5XIGCII', async () => { 24 | await driver.get('https://www.heywhatsthat.com/?view=P5XIGCII'); 25 | 26 | await sleep(2000); 27 | let elem = await mapDriver.activateAndWaitForScrollMapsLoaded(); 28 | // Execute scroll action 29 | await mapDriver.scrollIntoView(elem); 30 | await mapDriver.assertRuler('5 km'); 31 | 32 | // This scroll is a no-op, since we haven't clicked the map yet 33 | // It wouldn't scroll the page because the event is not trusted 34 | await mapDriver.scroll(elem, 0, -300); 35 | await mapDriver.click(); 36 | await assertLatLng([24.325, 0.01], [120.700, 0.01]); 37 | await mapDriver.click(); 38 | await sleep(1000); 39 | await assertLatLng([24.2627, 0.01], [120.7684, 0.01]); 40 | 41 | await mapDriver.scroll(elem, 0, -300); 42 | await mapDriver.click(); 43 | await sleep(2000); 44 | await assertLatLng([24.917977, 0.01], [120.769135, 0.01]); 45 | await mapDriver.assertRuler('5 km'); 46 | 47 | // Execute zoom action 48 | await mapDriver.pinchGesture(elem, 72); 49 | await sleep(2000); 50 | await mapDriver.click({ x: 150, y: 80 }); 51 | await sleep(1000); 52 | await mapDriver.assertRuler('20 km'); 53 | await assertLatLng([24.860665, 0.1], [121.11218, 0.01]); 54 | }); 55 | 56 | async function getLatLng() { 57 | const latlng = await driver.wait(async () => driver.findElement(By.id('map_latlon_div')), 10000); 58 | const text = await latlng.getText(); 59 | const pattern = /([\d.]+) N ([\d.]+) E/; 60 | const match = pattern.exec(text); 61 | if (!match) throw new Error(`Text "${text}" does not match lat lng pattern`); 62 | console.log('Got latitude, longitude =', text) 63 | const [_, lat, lng] = match.map(Number); 64 | return [lat, lng]; 65 | } 66 | 67 | async function assertLatLng(expectedLat, expectedLng) { 68 | const [lat, lng] = await getLatLng(); 69 | assertIn(lat, expectedLat); 70 | assertIn(lng, expectedLng); 71 | } 72 | }); 73 | -------------------------------------------------------------------------------- /test/auto/google_com_travel.mjs: -------------------------------------------------------------------------------- 1 | import { deepStrictEqual } from 'assert'; 2 | import { By } from 'selenium-webdriver'; 3 | import { MapDriver, sleep } from '../mapdriver.js'; 4 | 5 | const TEST_TIMEOUT = 10 * 60 * 1000; 6 | 7 | 8 | describe('google.com/travel test suite', function() { 9 | this.retries(2); 10 | this.slow(TEST_TIMEOUT); 11 | this.timeout(TEST_TIMEOUT); 12 | let driver; 13 | let mapDriver; 14 | 15 | before(async () => { 16 | mapDriver = await MapDriver.create(); 17 | driver = mapDriver.driver; 18 | }); 19 | after(async () => { 20 | await mapDriver.quit(); 21 | }) 22 | 23 | it('google.com/travel/explore', async () => { 24 | // While loading, Google Maps shows a version that's not fully 3D, which 25 | // sometimes causes subtle bugs in ScrollMaps. 26 | await driver.get('https://www.google.com/travel/explore'); 27 | await mapDriver.activateForGoogleDomain(); 28 | const elem = await mapDriver.waitForScrollMapsLoaded(); 29 | // Execute scroll action 30 | await waitForCities(['Chicago']); 31 | await sleep(2000); 32 | await mapDriver.scroll(elem, 180, -40); 33 | await waitForCities(['London']); 34 | deepStrictEqual( 35 | await findCities(['Chicago', 'London', 'Paris', 'Beijing']), 36 | ['London', 'Paris']); 37 | 38 | // Execute zoom action 39 | await mapDriver.pinchGesture(elem, 32); 40 | await waitForCities(['Chicago', 'London', 'Moscow']); 41 | 42 | await mapDriver.pinchGesture(elem, -32); 43 | await sleep(2000); 44 | deepStrictEqual( 45 | await findCities(['Chicago', 'London', 'Paris', 'Beijing']), 46 | ['London', 'Paris']); 47 | }); 48 | 49 | async function findCities(cities) { 50 | const xpath = cities.map(city => `//*[text()='${city}']`).join('|'); 51 | const elems = await driver.findElements(By.xpath(xpath)); 52 | const result = await Promise.all(elems.map(async elem => { 53 | try { 54 | return await elem.getText(); 55 | } catch (e) { 56 | return `ERROR: ${e}`; 57 | } 58 | })); 59 | return [...new Set(result.filter(x => x))].sort(); 60 | } 61 | 62 | async function waitForCities(cities) { 63 | process.stdout.write('Waiting for cities '); 64 | return await driver.wait(async () => { 65 | const elems = await findCities(cities); 66 | if (elems.length) { 67 | console.log(elems); 68 | return elems; 69 | } else { 70 | process.stdout.write('.'); 71 | return null; 72 | } 73 | }, 10000, `Cannot find cities ${cities}`); 74 | } 75 | }); 76 | -------------------------------------------------------------------------------- /src/permission.js: -------------------------------------------------------------------------------- 1 | const Permission = { 2 | getPermissions(urls) { 3 | return new Promise((resolve, reject) => { 4 | chrome.permissions.contains({ 'origins': urls }, resolve); 5 | }); 6 | }, 7 | async loadSiteStatus(urlString) { 8 | const url = new URL(urlString); 9 | let [isSiteGrantedResult, isAllGrantedResult] = await Promise.allSettled([ 10 | Permission.getPermissions([`${url.protocol}//${url.host}/`]), 11 | Permission.getPermissions(['']) 12 | ]); 13 | console.log('Site status: ', url, isSiteGrantedResult, isAllGrantedResult) 14 | isSiteGranted = isSiteGrantedResult.status === 'fulfilled' && isSiteGrantedResult.value; 15 | isAllGranted = isAllGrantedResult.status === 'fulfilled' && isAllGrantedResult.value; 16 | return { 17 | 'tabUrl': urlString, 18 | 'isSiteGranted': isSiteGranted, 19 | 'isAllGranted': isAllGranted 20 | }; 21 | }, 22 | 23 | canInjectIntoPage(url) { 24 | let protocol = new URL(url).protocol; 25 | return Permission.isOwnExtensionPage(url) || 26 | (protocol !== 'chrome:' 27 | && protocol !== 'chrome-extension:' 28 | && protocol !== 'about:' 29 | && protocol !== 'moz-extension:'); 30 | }, 31 | 32 | isOwnExtensionPage(url) { 33 | return url.indexOf(`chrome-extension://${chrome.runtime.id}`) === 0 34 | || url.indexOf(`moz-extension://${chrome.runtime.id}`) === 0; 35 | }, 36 | 37 | isMapsSite(url) { 38 | for (let domain of SCROLLMAPS_DOMAINS) { 39 | if (_matchPattern(domain, url)) { 40 | return true; 41 | } 42 | } 43 | return false; 44 | }, 45 | 46 | async requestFramePermission() { 47 | return await chrome.permissions.request({ origins: ['*://www.google.com/maps/embed'] }); 48 | }, 49 | }; 50 | 51 | const MATCH_PATTERN = /^(\*|http|https|file|ftp):\/\/(\*|(?:\*\.)?[^*/]*)(?:\/(.*))?$/; 52 | 53 | function _matchDomainPattern(pattern, url) { 54 | let regex = pattern.replace(MATCH_PATTERN, (match, scheme, host, path, offset, string) => { 55 | let result = ''; 56 | if (scheme === '*') { 57 | result += '(http|https)'; 58 | } else { 59 | result += scheme; 60 | } 61 | result += '://'; 62 | result += host.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&').replace('\\*', '[^\\./]*'); 63 | result += '($|/.*)'; 64 | return result; 65 | }); 66 | return !!url.match(regex); 67 | } 68 | 69 | function _matchPattern(pattern, url) { 70 | let regex = pattern.replace(MATCH_PATTERN, (match, scheme, host, path, offset, string) => { 71 | let result = ''; 72 | if (scheme === '*') { 73 | result += '(http|https)'; 74 | } else { 75 | result += scheme; 76 | } 77 | result += '://'; 78 | result += host.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&').replace('\\*', '[^\\./]*'); 79 | result += '(/'; 80 | result += path.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&').replace('\\*', '.*'); 81 | result += '|$)'; 82 | return result; 83 | }); 84 | return !!url.match(regex); 85 | } 86 | -------------------------------------------------------------------------------- /src/inject_frame_permission.js: -------------------------------------------------------------------------------- 1 | if (window.SM_FRAME_INJECT === undefined) { 2 | const DEBUG = chrome.runtime.getManifest().version === '10000'; 3 | window.SM_FRAME_INJECT = { count: 0 }; 4 | 5 | class GoogleMapIframeFinder { 6 | static findIframeMap() { 7 | const iframes = document.querySelectorAll('iframe[src^="https://www.google.com/maps/embed"]'); 8 | return iframes; 9 | } 10 | } 11 | 12 | async function checkIFramePermissions() { 13 | const iframes = GoogleMapIframeFinder.findIframeMap(); 14 | for (const frame of iframes) { 15 | if (!frame.hasAttribute('data-scrollmaps-frame')) { 16 | const container = document.createElement('div'); 17 | container.setAttribute('data-scrollmaps-perm-button', '1'); 18 | container.style.position = 'relative'; 19 | const shadow = container.attachShadow({ mode: "open" }); 20 | const btn = document.createElement('div'); 21 | btn.classList.add('sm-perm-btn'); 22 | btn.style.backgroundImage = 'url("' + chrome.runtime.getURL('images/permission_icon.png') + '")'; 23 | shadow.appendChild(btn); 24 | frame.insertAdjacentElement('beforebegin', container); 25 | 26 | const styleSheet = document.createElement('style'); 27 | styleSheet.innerHTML = ` 28 | .sm-perm-btn { 29 | position: absolute; top: 0px; right: 0px; 30 | width: 24px; height: 24px; 31 | margin: 8px; 32 | cursor: pointer; 33 | background-size: 24px 24px; 34 | filter: drop-shadow(0px 2px 8px rgba(0, 0, 0, 0.5)); 35 | } 36 | .sm-perm-btn:hover:after { 37 | content: 'ScrollMaps extension need additional permission to work in this embedded Google Maps'; 38 | position: absolute; top: 0px; right: 105%; 39 | font-size: 16px; 40 | width: 250px; 41 | padding: 4px; 42 | background: rgba(255, 255, 255, 0.9); 43 | border: 1px solid #ccc; 44 | border-radius: 5px; 45 | } 46 | `; 47 | shadow.appendChild(styleSheet); 48 | 49 | btn.onclick = async () => { 50 | let granted = await chrome.runtime.sendMessage( { action: 'requestIframePermission' }); 51 | console.log('request iframe perm', granted) 52 | if (granted) { 53 | btn.remove(); 54 | } 55 | }; 56 | frame.setAttribute('data-scrollmaps-frame', '1'); 57 | } 58 | } 59 | } 60 | 61 | function poll(func, timeout, count) { 62 | if (count <= 0) { 63 | return; 64 | } 65 | window.setTimeout(() => { 66 | if (!func()) { 67 | poll(func, timeout, count - 1); 68 | } 69 | }, timeout); 70 | } 71 | 72 | // Init 73 | let lastEventTime = 0; 74 | const THROTTLE_TIME_MS = 2000; 75 | window.addEventListener('wheel', async (e) => { 76 | if (e.timeStamp - lastEventTime > THROTTLE_TIME_MS) { 77 | await checkIFramePermissions(); 78 | lastEventTime = e.timeStamp; 79 | } 80 | }, true); 81 | poll(checkIFramePermissions, 2000, 3); 82 | } 83 | -------------------------------------------------------------------------------- /src/popup/popup.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ScrollMaps options 5 | 6 | 7 | 8 | 9 |
10 | 24 |
25 |
Activate ScrollMaps by clicking the extension icon
26 |
27 | 28 | 32 |
33 |
34 | 35 | 39 |
40 |
41 |
42 | 43 | 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /test/multimap-test.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ScrollMaps Test 5 | 41 | 42 | 43 | 44 | 96 | 97 | 98 | -------------------------------------------------------------------------------- /src/popup/popup.js: -------------------------------------------------------------------------------- 1 | document.addEventListener('DOMContentLoaded', async () => { 2 | 3 | const DEBUG = chrome.runtime.getManifest().version === '10000'; 4 | const siteStatus = loadSiteStatus(); 5 | 6 | function getTabUrl() { 7 | return new Promise((resolve, reject) => { 8 | chrome.tabs.query({active: true, currentWindow: true}, (tabs) => { 9 | if (tabs) { 10 | resolve(tabs[0].url); 11 | } else { 12 | reject('No active tab but browser action received'); 13 | } 14 | }); 15 | }); 16 | } 17 | 18 | async function loadSiteStatus() { 19 | return await Permission.loadSiteStatus(await getTabUrl()); 20 | } 21 | 22 | document.getElementById('reload').addEventListener('click', () => { 23 | chrome.runtime.reload(); 24 | return false; 25 | }, false); 26 | document.getElementById('reload').classList.toggle('hidden', !DEBUG); 27 | 28 | document.getElementById('options').addEventListener('click', () => { 29 | chrome.runtime.openOptionsPage(); 30 | window.close(); 31 | return false; 32 | }, false); 33 | 34 | document.getElementById('site_granted').addEventListener('change', async function() { 35 | const status = await siteStatus; 36 | if (this.checked) { 37 | let granted = await chrome.permissions.request({origins: [status.tabUrl]}); 38 | if (!granted) { 39 | this.checked = false; 40 | } 41 | } else { 42 | chrome.permissions.remove({origins: [status.tabUrl]}); 43 | } 44 | }, false); 45 | document.getElementById('all_granted').addEventListener('change', async function() { 46 | let allGranted = this.checked; 47 | if (allGranted) { 48 | let granted = await chrome.permissions.request({origins: ['']}); 49 | if (!granted) { 50 | allGranted = false; 51 | this.checked = false; 52 | } 53 | } else { 54 | chrome.permissions.remove({origins: ['']}) 55 | } 56 | document.getElementById('site_granted').checked = allGranted; 57 | refreshCheckboxEnabledStates(allGranted); 58 | }, false); 59 | 60 | function refreshCheckboxEnabledStates(allGranted) { 61 | document.getElementById('site_granted').disabled = allGranted; 62 | document.querySelector('label[for=site_granted]').classList.toggle('disabled', allGranted); 63 | } 64 | 65 | chrome.runtime.sendMessage({action: 'popupLoaded'}); 66 | 67 | const status = await siteStatus; 68 | if (Permission.isOwnExtensionPage(status.tabUrl)) { 69 | document.body.classList.add('disable-options'); 70 | document.getElementById('permissionExplanation').innerText = 71 | 'ScrollMaps is enabled on this ScrollMaps page.'; 72 | return; 73 | } 74 | if (!Permission.canInjectIntoPage(status.tabUrl)) { 75 | document.body.classList.add('disable-options'); 76 | const protocol = new URL(status.tabUrl).protocol; 77 | document.getElementById('permissionExplanation').innerText = 78 | `ScrollMaps cannot be enabled on "${protocol}" pages`; 79 | return; 80 | } 81 | const host = new URL(status.tabUrl).host; 82 | document.querySelector('label[for=site_granted] .PMcheckbox_smalltext') 83 | .innerText = `Enable ScrollMaps on ${host} without having to click on the extension icon`; 84 | 85 | document.getElementById('all_granted').checked = status.isAllGranted; 86 | document.getElementById('site_granted').checked = status.isSiteGranted; 87 | refreshCheckboxEnabledStates(status.isAllGranted); 88 | 89 | }, false); -------------------------------------------------------------------------------- /src/options/options.mjs: -------------------------------------------------------------------------------- 1 | import { PrefMaker } from '../prefmaker.mjs'; 2 | import { SCROLLMAPS_IFRAME_URL } from './maps_embed.mjs'; 3 | 4 | document.addEventListener('DOMContentLoaded', async () => { 5 | const mapsDemo = document.getElementById('mapsdemo'); 6 | mapsDemo.src = SCROLLMAPS_IFRAME_URL; 7 | 8 | const box = document.getElementById('checkboxes'); 9 | 10 | const enabledCheckbox = PrefMaker.makeBooleanCheckbox( 11 | 'enabled', 12 | 'Activate automatically', 13 | { 14 | true: 'Activate automatically on sites you have already granted permissions', 15 | false: 'Click on the extension icon to activate ScrollMaps manually' 16 | } 17 | ); 18 | box.appendChild(enabledCheckbox); 19 | 20 | const scrollSpeedSlider = PrefMaker.makeSlider('scrollSpeed', 'Scrolling speed', 500, 10, 10); 21 | box.appendChild(scrollSpeedSlider); 22 | 23 | const zoomSpeedSlider = PrefMaker.makeSlider('zoomSpeed', 'Zoom speed', 500, 10, 10); 24 | box.appendChild(zoomSpeedSlider); 25 | 26 | const invertScrollCheckbox = PrefMaker.makeBooleanCheckbox('invertScroll', 27 | 'Invert Scroll', 28 | 'Use the opposite direction as you do in your system preferences' 29 | ); 30 | box.appendChild(invertScrollCheckbox); 31 | 32 | const invertZoomDescription = 'Invert the direction when zooming with \u2318-scroll'; 33 | const invertZoomCheckbox = PrefMaker.makeBooleanCheckbox( 34 | 'invertZoom', 35 | 'Invert Zoom', 36 | invertZoomDescription 37 | ); 38 | box.appendChild(invertZoomCheckbox); 39 | 40 | const frameRequireFocusCheckbox = PrefMaker.makeBooleanCheckbox( 41 | 'frameRequireFocus', 42 | 'Require click to scroll embedded maps', 43 | 'Prioritize page scrolling until embedded map is clicked' 44 | ); 45 | box.appendChild(frameRequireFocusCheckbox); 46 | 47 | const allowAccessToAllSites = PrefMaker.makePermissionCheckbox( 48 | 'allowAccessToAllSites', 49 | '', 50 | 'Allow ScrollMaps on all sites', 51 | { 52 | true: 'ScrollMaps will enable on embedded Google Maps automatically', 53 | false: 'Click on the extension icon to activate ScrollMaps manually' 54 | } 55 | ); 56 | box.appendChild(allowAccessToAllSites); 57 | 58 | const zoomHint = document.createElement('div'); 59 | zoomHint.id = "zoomhint"; 60 | zoomHint.innerText = "Pinch to zoom in or out"; 61 | box.appendChild(zoomHint); 62 | 63 | const framePermissionMessage = document.getElementById('frame-permission-message'); 64 | const framePermButton = document.getElementById('frame-perm-btn'); 65 | framePermButton.onclick = async () => { 66 | let granted = await Permission.requestFramePermission(); 67 | if (granted) { 68 | chrome.runtime.sendMessage({ 'action': 'framePermissionGranted' }); 69 | await updateFramePermissionMessage(); 70 | } 71 | }; 72 | 73 | let lastFramePermissionGranted = true; 74 | 75 | async function updateFramePermissionMessage() { 76 | const framePermissionGranted = await chrome.permissions.contains({ origins: ["*://www.google.com/"] }); 77 | if (framePermissionGranted != lastFramePermissionGranted) { 78 | if (!framePermissionGranted) { 79 | framePermissionMessage.style.display = 'flex'; 80 | } else { 81 | framePermissionMessage.style.display = 'none'; 82 | const mapsDemo = document.getElementById('mapsdemo'); 83 | mapsDemo.src = SCROLLMAPS_IFRAME_URL; 84 | } 85 | lastFramePermissionGranted = framePermissionGranted; 86 | } 87 | } 88 | 89 | chrome.permissions.onAdded.addListener(updateFramePermissionMessage); 90 | chrome.permissions.onRemoved.addListener(updateFramePermissionMessage); 91 | await updateFramePermissionMessage(); 92 | }, false); 93 | -------------------------------------------------------------------------------- /test/auto/embedded_maps.mjs: -------------------------------------------------------------------------------- 1 | import assert from 'assert'; 2 | import { MapDriver, assertIn, sleep } from '../mapdriver.js'; 3 | import { By, until } from 'selenium-webdriver'; 4 | 5 | const TEST_TIMEOUT = 10 * 60 * 1000; 6 | 7 | 8 | describe('IFrame embed test suite', function () { 9 | this.retries(2); 10 | this.slow(TEST_TIMEOUT); 11 | this.timeout(TEST_TIMEOUT); 12 | let driver; 13 | let mapDriver; 14 | 15 | before(async () => { 16 | mapDriver = await MapDriver.create(); 17 | driver = mapDriver.driver; 18 | }); 19 | after(async () => { 20 | await mapDriver.quit(); 21 | }) 22 | 23 | it('https://developers.google.com/maps/documentation/embed', async () => { 24 | await driver.get('https://developers.google.com/maps/documentation/embed/get-started'); 25 | await mapDriver.clickBrowserAction(); 26 | 27 | const frameElem = await driver.wait(async () => { 28 | for (const elem of await driver.findElements(By.css('iframe'))) { 29 | if ((await elem.getAttribute('src')).indexOf('google.com/maps/embed') !== -1) { 30 | return elem; 31 | } 32 | } 33 | }, 10000, "Unable to find embedded maps"); 34 | await driver.executeScript((frameElem) => 35 | frameElem.scrollIntoView({ behavior: 'instant', block: 'center' }), frameElem); 36 | 37 | if (process.env.BROWSER === 'firefox') { 38 | try { 39 | const elem = await driver.wait(async () => (await driver.findElements(By.css("[data-scrollmaps-perm-button]")))[0], 5000); 40 | const requestPermissionButton = await (await elem.getShadowRoot()).findElements(By.className("sm-perm-btn")); 41 | const originalWindow = await driver.getWindowHandle(); 42 | await requestPermissionButton[0].click(); 43 | const windows = await driver.getAllWindowHandles(); 44 | const newWindow = windows.find(handle => handle !== originalWindow); 45 | await driver.switchTo().window(newWindow); 46 | const framePermBtn = await driver.wait(async () => (await driver.findElements(By.id("frame-perm-btn")))[0], 5000); 47 | await sleep(2000); 48 | await framePermBtn.click(); 49 | await mapDriver.firefoxAllowPermission(); 50 | await driver.switchTo().window(originalWindow); 51 | } catch (e) { 52 | console.warn("Error requesting permission", e); 53 | } 54 | } 55 | 56 | const assertLatLng = async (expectedLat, expectedLng) => { 57 | let [lat, lng] = await getIframeCoords(); 58 | console.log('iframe latlng', lat, lng) 59 | assertIn(lat, expectedLat); 60 | assertIn(lng, expectedLng); 61 | } 62 | 63 | await driver.switchTo().frame(frameElem); 64 | const elem = await mapDriver.waitForScrollMapsLoaded(); 65 | await assertLatLng([47.62, 0.1], [-122.3492, 0.1]); 66 | await mapDriver.scroll(elem, 300, 500); // Scroll should do nothing – map is not activated 67 | await sleep(1000); 68 | await assertLatLng([47.62, 0.1], [-122.3492, 0.1]); 69 | await elem.click(); 70 | await sleep(1000); 71 | 72 | await mapDriver.scroll(elem, 300, 500); 73 | await sleep(2000); 74 | await assertLatLng([47.606408, 0.1], [-122.336721, 0.1]); 75 | }); 76 | 77 | async function getIframeCoords() { 78 | const largerMapLink = await driver.wait(until.elementLocated(By.css(".google-maps-link a, a.google-maps-link"))); 79 | const href = await largerMapLink.getAttribute("href"); 80 | const linkUrl = new URL(href); 81 | return linkUrl.searchParams.get('ll').split(',', 2).map(Number); 82 | } 83 | 84 | async function getIframeZoom() { 85 | const largerMapLink = await driver.wait(until.elementLocated(By.css(".google-maps-link a, a.google-maps-link"))); 86 | const href = await largerMapLink.getAttribute("href"); 87 | const linkUrl = new URL(href); 88 | return Number(linkUrl.searchParams.get('z')); 89 | } 90 | }); 91 | -------------------------------------------------------------------------------- /test/chrome_browser_action.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/osascript -l JavaScript 2 | 3 | // Applescript (JXA) to click on the browser action for ScrollMaps. 4 | // Works on Macs only, obviously. 5 | 6 | const app = Application.currentApplication(); 7 | app.includeStandardAdditions = true; 8 | 9 | clickBrowserAction("ScrollMaps"); 10 | 11 | function clickBrowserAction(extensionName) { 12 | const systemEvents = Application("System Events"); 13 | const pid = app.systemAttribute("TEST_PROCESS"); 14 | const browser = app.systemAttribute("BROWSER"); 15 | const chromeProcess = systemEvents.processes.where({ unixId: pid })[0]; 16 | chromeProcess.frontmost = true; 17 | let extensionButton; 18 | if (browser === 'chrome') { 19 | const toolbar = chromeProcess.windows[0].groups[0].groups[0].groups[0].groups[0].toolbars[0]; 20 | // Uncomment this line to find the extensions button (finding from the entire browser window is slow) 21 | // dump(findElement(chromeProcess.windows[0], "Extensions")[0]); 22 | extensionButton = findInArray(toolbar.popUpButtons, x => x.accessibilityDescription() == "Extensions"); 23 | } else if (browser === 'edge') { 24 | const toolbar = chromeProcess.windows[0].groups[0].groups[0].groups[0].groups[0].toolbars[0]; 25 | // Uncomment this line to find the extensions button (finding from the entire browser window is slow) 26 | // dump(findElement(chromeProcess.windows[0], "Extensions")[0]); 27 | extensionButton = findInArray(flatMap(toolbar.groups, (g) => g.buttons), x => x.accessibilityDescription() == "Extensions"); 28 | } 29 | if (typeof extensionButton !== 'function') { 30 | console.log('Cannot find extension button'); 31 | } 32 | extensionButton.actions['AXPress'].perform(); 33 | let browserAction = findRecursive(chromeProcess.windows[0], e => e.description() == extensionName, "button"); 34 | if (typeof browserAction !== 'function') { 35 | console.log('Cannot find browser action button'); 36 | } 37 | browserAction.actions['AXPress'].perform(); 38 | } 39 | 40 | function flatMap(arr, mapFn) { 41 | const result = []; 42 | for (let i = 0; i < arr.length; i++) { 43 | let mapResult = mapFn(arr[i]) || []; 44 | for (let j = 0; j < mapResult.length; j++) { 45 | result.push(mapResult[j]); 46 | } 47 | } 48 | return result; 49 | } 50 | 51 | function findInArray(arr, filter) { 52 | for (let i = 0; i < arr.length; i++) { 53 | if (filter(arr[i])) { 54 | return arr[i]; 55 | } 56 | } 57 | } 58 | 59 | function findRecursive(e, predicate, predicateclass, eclass) { 60 | try { 61 | if (predicateclass && eclass && eclass === predicateclass && predicate(e)) { 62 | return e; 63 | } 64 | } catch (e) { 65 | console.log('Failed to run predicate', e); 66 | return undefined; 67 | } 68 | // A normal iteration through e.uiElements doesn't work because 69 | // the selector returned filters the process by name "Google Chrome" 70 | // not by the UID. 71 | const counts = {}; 72 | for (const cls of e.uiElements.class()) { 73 | if (cls) { 74 | const i = counts[cls] || 0; 75 | counts[cls] = i + 1; 76 | const child = e[pluralize(cls)][i]; 77 | const result = findRecursive(child, predicate, predicateclass, cls); 78 | if (result) { 79 | return result; 80 | } 81 | } 82 | } 83 | } 84 | 85 | function pluralize(cls) { 86 | if (cls === 'checkbox') return 'checkboxes'; 87 | return cls + 's'; 88 | } 89 | 90 | function findElement(windows, description) { 91 | for (let i = 0; i < windows.length; i++) { 92 | const win = windows[i]; 93 | const entireContents = win.entireContents(); 94 | for (const content of entireContents) { 95 | try { 96 | if (content.name() === description) { 97 | return content; 98 | } 99 | if (content.accessibilityDescription() === description) { 100 | return content; 101 | } 102 | } catch (e) { 103 | console.log('Error getting description of UI element', e, "for", Automation.getDisplayString(content)); 104 | } 105 | } 106 | } 107 | } 108 | 109 | function dumpcontents(obj) { 110 | for (const x of obj.entireContents()) { 111 | console.log("================"); 112 | dumpprops(x) 113 | console.log(">>>>>>>>>>>>>>>>"); 114 | } 115 | } 116 | 117 | function dumpprops(obj) { 118 | if (!('properties' in obj)) return; 119 | const props = obj.properties(); 120 | for (const k in props) { 121 | console.log(k, " = ", props[k]); 122 | } 123 | } 124 | 125 | function dump(obj) { 126 | const str = Automation.getDisplayString(obj); 127 | const replaced = str.replace(/"\w+":/g, (g) => "\n" + g) 128 | console.log(replaced); 129 | } 130 | -------------------------------------------------------------------------------- /test/auto/google_com_maps.mjs: -------------------------------------------------------------------------------- 1 | import { MapDriver, sleep } from '../mapdriver.js'; 2 | 3 | const TEST_TIMEOUT = 10 * 60 * 1000; 4 | 5 | 6 | describe('google.com/maps test suite', function () { 7 | this.retries(2); 8 | this.slow(TEST_TIMEOUT); 9 | this.timeout(TEST_TIMEOUT); 10 | let driver; 11 | let mapDriver; 12 | 13 | before(async () => { 14 | mapDriver = await MapDriver.create(); 15 | driver = mapDriver.driver; 16 | }); 17 | after(async () => { 18 | await mapDriver.quit(); 19 | }) 20 | 21 | it('google.com/maps (while loading)', async () => { 22 | // While loading, Google Maps shows a version that's not fully 3D, which 23 | // sometimes causes subtle bugs in ScrollMaps. 24 | await driver.get('https://www.google.com/maps/@37,-122,14z?force=webgl'); 25 | await mapDriver.activateForGoogleDomain(); 26 | const elem = await mapDriver.waitForScrollMapsLoaded(); 27 | // Execute scroll action 28 | await mapDriver.scroll(elem, 300, 500); 29 | await assertUrlParams({ 30 | lat: [36.87, 36.97], 31 | lng: [-121.98, -121.9], 32 | zoom: [14, 14], 33 | logTag: "while loading", 34 | }); 35 | 36 | // Execute zoom action 37 | await mapDriver.pinchGesture(elem, 64); 38 | await assertUrlParams({ 39 | lat: [36.87, 36.97], 40 | lng: [-121.98, -121.9], 41 | zoom: [5, 11] 42 | }); 43 | 44 | await mapDriver.pinchGesture(elem, -64); 45 | await assertUrlParams({ 46 | lat: [36.87, 36.97], 47 | lng: [-121.98, -121.9], 48 | zoom: [13, 15], 49 | logTag: "after pinch" 50 | }); 51 | }); 52 | 53 | it('google.com/maps', async () => { 54 | await driver.get('https://www.google.com/maps/@37,-122,14z?force=webgl'); 55 | await mapDriver.activateForGoogleDomain(); 56 | const elem = await mapDriver.waitForCanvasMapsLoaded('webgl'); 57 | // Execute scroll action 58 | await mapDriver.scroll(elem, 300, 500); 59 | await assertUrlParams({ 60 | lat: [36.9, 36.97], 61 | lng: [-121.98, -121.9], 62 | zoom: [14, 14], 63 | logTag: "After scrolling", 64 | }); 65 | // Execute zoom action 66 | await mapDriver.pinchGesture(elem, 64); 67 | await assertUrlParams({ 68 | lat: [36.9, 36.97], 69 | lng: [-121.98, -121.9], 70 | zoom: [5, 11], 71 | logTag: "After pinch zoom in", 72 | }); 73 | 74 | await mapDriver.pinchGesture(elem, -64); 75 | await assertUrlParams({ 76 | lat: [36.9, 36.97], 77 | lng: [-121.98, -121.9], 78 | zoom: [13, 15], 79 | logTag: "After pinch zoom out", 80 | }); 81 | }); 82 | 83 | it('google.com/maps (canvas)', async () => { 84 | await driver.get('https://www.google.com/maps/@37,-122,14z?force=canvas'); 85 | await mapDriver.activateForGoogleDomain(); 86 | const elem = await mapDriver.waitForCanvasMapsLoaded('2d'); 87 | // Execute scroll action 88 | await mapDriver.scroll(elem, 300, 500); 89 | await assertUrlParams({ 90 | lat: [36.9, 36.97], 91 | lng: [-121.98, -121.9], 92 | zoom: [14, 14], 93 | logTag: "canvas: after scroll", 94 | }); 95 | // Execute zoom action 96 | await mapDriver.pinchUntil(elem, 64, async () => await isUrlCoordsWithin({ 97 | lat: [36.9, 36.97], 98 | lng: [-121.98, -121.9], 99 | zoom: [5, 7], 100 | })); 101 | 102 | await mapDriver.pinchUntil(elem, -64, async () => await isUrlCoordsWithin({ 103 | lat: [36.9, 36.97], 104 | lng: [-121.98, -121.9], 105 | zoom: [16, 20], 106 | })); 107 | }); 108 | 109 | async function getUrlLatLngZoom() { 110 | const url = await driver.getCurrentUrl(); 111 | const pattern = new RegExp('https://.*/@(-?[\\d\\.]+),(-?[\\d\\.]+),([\\d\\.]+)z.*'); 112 | const match = pattern.exec(url); 113 | if (!match) return [undefined, undefined, undefined]; 114 | const [_, lat, lng, zoom] = match.map(Number); 115 | return { lat: lat, lng: lng, zoom: zoom }; 116 | } 117 | 118 | async function isUrlCoordsWithin({ lat, lng, zoom }) { 119 | const rangeContains = ([min, max], val) => min <= val && val <= max; 120 | const urlParams = await getUrlLatLngZoom(); 121 | console.log('URL params=', urlParams); 122 | return rangeContains(lat, urlParams.lat) && 123 | rangeContains(lng, urlParams.lng) && 124 | rangeContains(zoom, urlParams.zoom); 125 | } 126 | 127 | async function assertUrlParams({ lat, lng, zoom, logTag }) { 128 | for (let i = 0; i < 10; i++) { 129 | if (await isUrlCoordsWithin({ lat, lng, zoom, logTag })) { 130 | return; 131 | } 132 | await sleep(1000); 133 | } 134 | throw new Error(`[${logTag}] Failed to wait for URL params to be within range ${lat} ${lng} ${zoom}`); 135 | } 136 | }); 137 | -------------------------------------------------------------------------------- /test/manual/manual_test.js: -------------------------------------------------------------------------------- 1 | const assert = require('assert'); 2 | const webdriver = require('selenium-webdriver'); 3 | const chrome = require('selenium-webdriver/chrome'); 4 | const firefox = require('selenium-webdriver/firefox'); 5 | const process = require('process'); 6 | require('chromedriver'); 7 | require('geckodriver'); 8 | 9 | const TEST_TIMEOUT = 10 * 60 * 1000; 10 | 11 | 12 | describe('Manual test suite', function() { 13 | console.log(` 14 | This is a manual test case. Go through each tab and make sure ScrollMap 15 | works correctly on each of them. Press Ctrl-Esc once you are done testing 16 | with that page.`) 17 | this.slow(TEST_TIMEOUT); 18 | this.timeout(TEST_TIMEOUT); 19 | let driver; 20 | 21 | before(async () => { 22 | if (process.env.BROWSER === 'chrome') { 23 | driver = new webdriver.Builder() 24 | .forBrowser('chrome') 25 | .setChromeOptions( 26 | new chrome.Options() 27 | .addArguments(`load-extension=${process.cwd()}/gen/plugin-10000-chrome`) 28 | ) 29 | .build(); 30 | } else if (process.env.BROWSER === 'firefox') { 31 | driver = new webdriver.Builder() 32 | .forBrowser('firefox') 33 | .setFirefoxOptions(new firefox.Options()) 34 | .build(); 35 | await driver.installAddon(`${process.cwd()}/gen/scrollmaps-10000-firefox.zip`, true) 36 | } else { 37 | throw 'Environment variable $BROWSER not defined'; 38 | } 39 | driver.manage().setTimeouts({'script': TEST_TIMEOUT}); 40 | }); 41 | after(async () => { 42 | await driver.quit(); 43 | }) 44 | 45 | const TEST_SITES = [ 46 | // Google maps 47 | 'https://www.google.com/maps?force=webgl', 48 | 'https://developers.google.com/maps/documentation/javascript/styling', 49 | 'https://developers.google.com/maps/documentation/embed/guide', 50 | 'https://developers.google.com/maps/documentation/javascript/examples/polygon-draggable', 51 | 'https://developers.google.com/maps/documentation/javascript/examples/layer-data-quakes', 52 | 'https://developers.google.com/maps/documentation/javascript/examples/layer-georss', 53 | 'https://developers.google.com/maps/documentation/javascript/examples/streetview-embed', 54 | 'https://developers.google.com/maps/documentation/javascript/examples/drawing-tools', 55 | 'https://www.google.com/maps?force=canvas', 56 | 'https://www.google.com/maps/d/u/0/viewer?msa=0&mid=1ntHquqDTqNB6fcmjKDSJT3VusG0&ll=37.34262853432693%2C-121.3232905&z=7', 57 | 'https://www.google.com/maps/@37.4219933,-122.0839072,3a,75y,8.52h,91.87t/data=!3m7!1e1!3m5!1sAF1QipMTIbIwyp8-XiyAGV95fPGmHuKi-lZkyUsliSVH!2e10!3e11!7i10000!8i5000', 58 | 'http://la.smorgasburg.com/info/', 59 | 'https://www.yelp.com/search?find_desc=Restaurants&find_loc=Chicago%2C%20IL', 60 | 'https://www.google.com/travel/explore', 61 | 'https://www.heywhatsthat.com/?view=P5XIGCII', 62 | // ArcGis 63 | // More demos at https://www.arcgis.com/apps/instant/filtergallery/index.html?appid=2833a9ccc8e648bc9bb8383c00694acf 64 | 'https://www.arcgis.com/home/webmap/viewer.html', 65 | 'https://sccplanning.maps.arcgis.com/apps/webappviewer/index.html?id=7d5a189b138e4aa3bea6dc0514f0b85b', 66 | 'https://geoxc-apps2.bd.esri.com/LivingAtlas/GlobalLandCoverChangePrediction/index.html', 67 | 'https://geoxc-apps2.bd.esri.com/Analysis/DistanceToInfrastructure/index.html', 68 | // Mapbox 69 | 'https://docs.mapbox.com/mapbox-gl-js/example/simple-map/', 70 | 'http://en.parkopedia.com/parking/san_francisco_ca_united_states/?ac=1&country=US&lat=37.7749295&lng=-122.41941550000001', 71 | 'https://labs.mapbox.com/standard-style/#16.2/48.859605/2.293506/-20/62', 72 | 'https://www.wunderground.com/wundermap', 73 | 'https://www.napavalley.com/businesses/42931/napa-s-riverfront', 74 | // Apple MapKit 75 | 'https://duckduckgo.com/?q=maps&iaxm=maps&source=maps', 76 | 'https://maps.apple.com/imagecollection/map?path=london', 77 | 'https://developer.apple.com/maps/web/', 78 | // MapLibre 79 | // More at https://github.com/maplibre/awesome-maplibre?tab=readme-ov-file#users 80 | 'https://maplibre.org/maplibre-gl-js/docs/', 81 | 'https://travelermap.net/parks/usa#map=10.2/37.6926/-121.9915', 82 | 'https://samples.azuremaps.com/animations/morph-shape-animation', 83 | // OpenLayer 84 | 'https://openlayers.org/en/latest/examples/mapbox-vector-tiles-advanced.html', 85 | ] 86 | 87 | for (const site of TEST_SITES) { 88 | it(`Site: ${site}`, async () => { 89 | await driver.get(site); 90 | await waitForEnd(driver); 91 | }); 92 | } 93 | }); 94 | 95 | 96 | function sleep(timeout) { 97 | return new Promise((resolve, reject) => setTimeout(resolve, timeout)); 98 | } 99 | 100 | async function waitForEnd(driver) { 101 | return await driver.executeAsyncScript((done) => { 102 | document.addEventListener('keyup', (e) => { 103 | if (e.key === 'Escape' && e.ctrlKey) { 104 | done(); 105 | } 106 | }, true); 107 | }); 108 | } 109 | -------------------------------------------------------------------------------- /src/prefmaker.mjs: -------------------------------------------------------------------------------- 1 | /** Create views or widgets to toggle certain preference values. */ 2 | 3 | export class PrefMaker { 4 | 5 | static makePermissionCheckbox(key, origin, label, secondLine) { 6 | if (typeof secondLine === 'string') { 7 | label = this._createTwoLineBox(label, secondLine); 8 | } else if (typeof secondLine === 'object') { 9 | // secondLine can also be in the form 10 | // { true: 'string when enabled', false: 'string when disabled' } 11 | label = this._createTwoLineBox(label, secondLine[false]); 12 | } 13 | const div = document.createElement('div'); 14 | div.classList.add('PMcheckbox'); 15 | const box = document.createElement('input'); 16 | box.id = 'PMcheckbox_' + key; 17 | box.type = 'checkbox'; 18 | const labelElem = document.createElement('label'); 19 | labelElem.htmlFor = 'PMcheckbox_' + key; 20 | labelElem.appendChild(label); 21 | div.appendChild(box); 22 | div.appendChild(labelElem); 23 | box.addEventListener('change', updateOption, false); 24 | updateView(); 25 | 26 | function updateOption(){ 27 | if (box.checked) { 28 | chrome.permissions.request({origins: [origin]}, () => updateView()); 29 | } else { 30 | chrome.permissions.remove({origins: [origin]}, () => updateView()); 31 | } 32 | } 33 | async function updateView() { 34 | const permission = await Permission.getPermissions([origin]); 35 | box.checked = permission; 36 | if (typeof secondLine === 'object') { 37 | label.querySelector('.PMcheckbox_smalltext').innerText = secondLine[permission]; 38 | } 39 | } 40 | chrome.permissions.onAdded.addListener(updateView); 41 | chrome.permissions.onRemoved.addListener(updateView); 42 | 43 | return div; 44 | } 45 | 46 | static makeBooleanCheckbox(key, label, secondLine) { 47 | if (typeof secondLine === 'string') { 48 | label = this._createTwoLineBox(label, secondLine); 49 | } else if (typeof secondLine === 'object') { 50 | // secondLine can also be in the form 51 | // { true: 'string when enabled', false: 'string when disabled' } 52 | label = this._createTwoLineBox(label, secondLine[false]); 53 | } 54 | const div = document.createElement('div'); 55 | div.classList.add('PMcheckbox'); 56 | const box = document.createElement('input'); 57 | box.id = 'PMcheckbox_' + key; 58 | box.type = 'checkbox'; 59 | const labelElem = document.createElement('label'); 60 | labelElem.htmlFor = box.id; 61 | labelElem.appendChild(label); 62 | div.appendChild(box); 63 | div.appendChild(labelElem); 64 | box.addEventListener('change', updateOption, false); 65 | updateView(false); 66 | 67 | let prefChange = false; 68 | Pref.onPreferenceChanged(key, async (key, value) => { 69 | await updateView(prefChange); 70 | prefChange = false; 71 | }); 72 | 73 | function updateOption() { 74 | prefChange = true; 75 | Pref.setOption(key, box.checked); 76 | } 77 | async function updateView(prefChange) { 78 | const prefValue = await pref(key); 79 | if (!prefChange) { 80 | box.checked = prefValue; 81 | } 82 | if (typeof secondLine === 'object') { 83 | labelElem.querySelector('.PMcheckbox_smalltext').innerText = secondLine[prefValue]; 84 | } 85 | } 86 | 87 | return div; 88 | } 89 | 90 | static makeSlider(key, label, max, min, step) { 91 | step = step || 1; 92 | const div = document.createElement('div'); 93 | div.classList.add('PMslider'); 94 | const slider = document.createElement('input'); 95 | slider.type = 'range'; 96 | slider.id = `PMslider_${key}`; 97 | slider.max = max; 98 | slider.min = min; 99 | slider.step = step; 100 | const preview = document.createElement('span'); 101 | preview.id = `PMsliderPreview_${key}`; 102 | preview.classList.add('PMsliderPreview'); 103 | const labelElem = document.createElement('label'); 104 | labelElem.htmlFor = slider.id; 105 | labelElem.innerText = label; 106 | div.appendChild(labelElem); 107 | div.appendChild(slider); 108 | div.appendChild(preview); 109 | let prefChange = false; 110 | 111 | slider.addEventListener('change', async () => { 112 | prefChange = true; 113 | await Pref.setOption(key, slider.value); 114 | preview.innerText = await pref(key); 115 | }, false); 116 | slider.addEventListener('input', () => { preview.innerText = slider.value; }, false) 117 | updateView(); 118 | 119 | Pref.onPreferenceChanged(key, async (key, value) => { 120 | if(!prefChange) { 121 | await updateView(value); 122 | } 123 | prefChange = false; 124 | }); 125 | 126 | async function updateView() { 127 | slider.value = await pref(key); 128 | preview.innerText = await pref(key); 129 | } 130 | 131 | return div; 132 | } 133 | 134 | static _createTwoLineBox(label, secondLine) { 135 | const wrap = document.createElement('div'); 136 | wrap.classList.add('PMcheckbox_labelwrap'); 137 | const line1 = document.createElement('div'); 138 | line1.classList.add('PMcheckbox_labeltext'); 139 | line1.innerText = label; 140 | wrap.appendChild(line1); 141 | const line2 = document.createElement('div'); 142 | line2.classList.add('PMcheckbox_smalltext'); 143 | line2.innerText = secondLine; 144 | wrap.appendChild(line2); 145 | return wrap; 146 | } 147 | 148 | } 149 | -------------------------------------------------------------------------------- /src/Scrollability.js: -------------------------------------------------------------------------------- 1 | if (window.Scrollability === undefined) { 2 | const DEBUG = chrome.runtime.getManifest().version === '10000'; 3 | window.Scrollability = { 4 | // Whether an element is scrollable 5 | isScrollable(element) { 6 | if (!element || !element.ownerDocument) return false; 7 | if (element.scrollHeight <= element.clientHeight) return false; 8 | // if (element.clientHeight === 0 || element.clientWidth === 0) return false; 9 | 10 | const overflow = window.getComputedStyle(element).getPropertyValue('overflow'); 11 | if (overflow === 'hidden') return false; 12 | // Body and document element will scroll even if overflow is visible 13 | if (element === document.body || element === document.documentElement) return true; 14 | return overflow !== 'visible'; 15 | }, 16 | 17 | // hasScrollableParent(elem) ==> whether anything, including window scrolls 18 | // hasScrollableParent(elem, until) ==> whether any parent up to "until" scrolls 19 | hasScrollableParent(element, until) { 20 | // This short-circuiting fails if there is an element in between that has position:fixed 21 | // if (until === undefined && Scrollability.isWindowScrollable()) return true; 22 | return Scrollability._hasScrollableParentInner(element, until); 23 | }, 24 | 25 | _hasScrollableParentInner(element, until) { 26 | if (this.isScrollable(element)) return true; 27 | if (!element || !element.parentNode) return false; 28 | if (getComputedStyle(element).position === 'fixed') return false; 29 | if (until && (element === until || element.isSameNode(until))) return false; 30 | return this._hasScrollableParentInner(element.parentNode, until); 31 | }, 32 | 33 | isWindowScrollable() { 34 | let hasContentBelowFold = outerHeight(document.documentElement) + 35 | document.documentElement.offsetTop > window.innerHeight; 36 | hasContentBelowFold |= outerHeight(document.body) + 37 | document.body.offsetTop > window.innerHeight; 38 | const bodyStyle = window.getComputedStyle(document.body); 39 | const documentStyle = window.getComputedStyle(document.documentElement); 40 | return hasContentBelowFold && 41 | bodyStyle['overflow'] !== 'hidden' && 42 | documentStyle['overflow'] !== 'hidden'; 43 | 44 | function outerHeight(el) { 45 | const styles = window.getComputedStyle(el); 46 | const margin = parseFloat(styles['marginTop']) + parseFloat(styles['marginBottom']); 47 | return Math.ceil(el.offsetHeight + margin); 48 | } 49 | }, 50 | 51 | _monitorPotentialScrollabilityChange(element, callback) { 52 | if (DEBUG) { 53 | window.addEventListener('keydown', function (e) { 54 | if (e.keyCode === 192) { // ` 55 | console.log('force refreshing scrollability'); 56 | callback(); 57 | } 58 | }); 59 | } 60 | 61 | window.addEventListener('resize', callback); 62 | document.addEventListener('load', callback); 63 | }, 64 | 65 | // Monitor parent scrollability for given element across iframes 66 | monitorScrollabilitySuper(element, callback) { 67 | let overallScrollable = null; 68 | let ancestorScrollable = false; // Scrollability of parent documents of this frame 69 | 70 | const updateScrollability = () => { 71 | // Maybe not all cases need to calculate hasScrollableParent? 72 | var newOverallScrollable = ancestorScrollable || Scrollability.hasScrollableParent(element); 73 | if (overallScrollable !== newOverallScrollable) { 74 | overallScrollable = newOverallScrollable; 75 | callback(newOverallScrollable); 76 | } 77 | }; 78 | 79 | if (window !== window.parent) { 80 | let parentScrollabilityBackoff = 500; 81 | let parentResultReceived = false; 82 | 83 | let askParentFrameForScrollability = () => { 84 | if (parentResultReceived || parentScrollabilityBackoff >= 10000) { 85 | return; 86 | } 87 | parentScrollabilityBackoff *= 2; 88 | // Register cross-iframe scroll monitoring 89 | window.parent.postMessage({'action': 'monitorScroll'}, '*'); 90 | window.setTimeout(askParentFrameForScrollability, parentScrollabilityBackoff); 91 | } 92 | 93 | askParentFrameForScrollability(); 94 | 95 | window.addEventListener('message', (message) => { 96 | parentResultReceived = true; 97 | if (message.data.action === 'pageNeedsScrolling') { 98 | ancestorScrollable = Boolean(message.data.value); 99 | updateScrollability(); 100 | } 101 | }); 102 | } else { 103 | ancestorScrollable = false; 104 | updateScrollability(); 105 | } 106 | 107 | Scrollability._monitorPotentialScrollabilityChange(element, updateScrollability); 108 | } 109 | }; 110 | 111 | function getIframeForWindow(win) { 112 | for (const iframe of document.getElementsByTagName('iframe')) { 113 | if (iframe.contentWindow === win) { 114 | return iframe; 115 | } 116 | } 117 | } 118 | 119 | // Init 120 | 121 | window.addEventListener('message', function(message) { 122 | if (message.data.action === 'monitorScroll') { 123 | const iframe = getIframeForWindow(message.source); 124 | if (!iframe) { 125 | console.warn('No matching iframe for message', message); 126 | return; 127 | } 128 | 129 | Scrollability.monitorScrollabilitySuper(iframe, function (scrollable) { 130 | message.source.postMessage({'action': 'pageNeedsScrolling', 'value': scrollable}, '*'); 131 | }); 132 | } 133 | }); 134 | } 135 | -------------------------------------------------------------------------------- /test/auto/options_page.mjs: -------------------------------------------------------------------------------- 1 | import assert from 'assert'; 2 | import { By, until } from 'selenium-webdriver'; 3 | import { MapDriver, assertIn, sleep } from '../mapdriver.js'; 4 | 5 | const TEST_TIMEOUT = 10 * 60 * 1000; 6 | 7 | 8 | describe('Extension options page', function () { 9 | this.retries(1); 10 | this.slow(TEST_TIMEOUT); 11 | this.timeout(TEST_TIMEOUT); 12 | let driver; 13 | let mapDriver; 14 | 15 | before(async () => { 16 | mapDriver = await MapDriver.create(); 17 | driver = mapDriver.driver; 18 | }); 19 | after(async () => { 20 | await mapDriver.quit(); 21 | }) 22 | 23 | it('options page', async () => { 24 | await openOptionsPage(); 25 | await driver.switchTo().frame(driver.findElement(By.id("mapsdemo"))); 26 | const elem = await mapDriver.waitForScrollMapsLoaded(); 27 | await assertLatLng([37.3861, 0.01], [-122.0839, 0.01]); 28 | await mapDriver.scroll(elem, 500, -80); 29 | await sleep(1000); 30 | await assertLatLng([37.444342, 0.01], [-121.452895, 0.01]); 31 | }); 32 | 33 | it('increase scroll speed', async () => { 34 | await openOptionsPage(); 35 | 36 | const scrollSpeedSlider = await driver.findElement(By.id('PMslider_scrollSpeed')); 37 | await setSlider(scrollSpeedSlider, 400); 38 | await sleep(500); 39 | 40 | await driver.switchTo().frame(driver.findElement(By.id("mapsdemo"))); 41 | const elem = await mapDriver.waitForScrollMapsLoaded(); 42 | await assertLatLng([37.3861, 0.01], [-122.0839, 0.01]); 43 | await mapDriver.scroll(elem, 300, -40); 44 | await sleep(1000); 45 | await assertLatLng([37.41351, 0.01], [-121.696581, 0.05]); 46 | }); 47 | 48 | it('invert scroll', async () => { 49 | await openOptionsPage(); 50 | 51 | let invertScrollCheckbox = await driver.findElement(By.id('PMcheckbox_invertScroll')); 52 | if (!await invertScrollCheckbox.getAttribute('checked')) { 53 | await invertScrollCheckbox.click(); 54 | } 55 | 56 | await driver.switchTo().frame(driver.findElement(By.id("mapsdemo"))); 57 | const elem = await mapDriver.waitForScrollMapsLoaded(); 58 | await assertLatLng([37.3861, 0.01], [-122.0839, 0.01]); 59 | await mapDriver.scroll(elem, 300, -40); 60 | await sleep(1000); 61 | await assertLatLng([37.356442, 0.01], [-122.496387, 0.01]); 62 | }); 63 | 64 | it('zoom', async () => { 65 | await openOptionsPage(); 66 | 67 | await driver.switchTo().frame(driver.findElement(By.id("mapsdemo"))); 68 | const elem = await mapDriver.waitForScrollMapsLoaded(); 69 | await assertLatLng([37.3861, 0.01], [-122.0839, 0.01]); 70 | assert.equal(await getIframeZoom(), 12); 71 | await mapDriver.scroll(elem, 0, 100, { metaKey: true, logTag: 'Zooming' }); 72 | await sleep(1000); 73 | assert.equal(await getIframeZoom(), 10); 74 | }); 75 | 76 | it('invert zoom', async () => { 77 | await openOptionsPage(); 78 | 79 | let invertZoomCheckbox = await driver.findElement(By.id('PMcheckbox_invertZoom')); 80 | if (!await invertZoomCheckbox.getAttribute('checked')) { 81 | await invertZoomCheckbox.click(); 82 | } 83 | 84 | await driver.switchTo().frame(driver.findElement(By.id("mapsdemo"))); 85 | const elem = await mapDriver.waitForScrollMapsLoaded(); 86 | await assertLatLng([37.3861, 0.01], [-122.0839, 0.01]); 87 | assert.equal(await getIframeZoom(), 12); 88 | await mapDriver.scroll(elem, 0, 100, { metaKey: true, logTag: 'Zooming' }); 89 | await sleep(1000); 90 | assert.equal(await getIframeZoom(), 14); 91 | }); 92 | 93 | let firefoxExtensionUrl; 94 | 95 | async function openOptionsPage() { 96 | if (process.env.BROWSER === 'chrome') { 97 | await driver.get('chrome-extension://fhmmcoabkeceafmokkpgddnmmkhjlenl/src/options/options.html'); 98 | } else if (process.env.BROWSER === 'edge') { 99 | await driver.get('chrome-extension://ipkkinfjghncepalhlppcjfedcdojfha/src/options/options.html'); 100 | } else if (process.env.BROWSER === 'firefox') { 101 | if (firefoxExtensionUrl) { 102 | await driver.get(firefoxExtensionUrl); 103 | } else { 104 | await driver.get('about:addons'); 105 | await driver.findElement(By.name('extension')).click(); 106 | const originalWindow = await driver.getWindowHandle(); 107 | const scrollMapsItem = await driver.findElement(By.css(`[addon-id="${mapDriver.extras.extensionId}"]`)); 108 | await scrollMapsItem.findElement(By.className('more-options-button')).click(); 109 | try { 110 | await scrollMapsItem.findElement(By.css('[action="preferences"]')).click(); 111 | } catch (e) { 112 | // console.log(e); 113 | } 114 | const windows = await driver.getAllWindowHandles(); 115 | const newWindow = windows.find(handle => handle !== originalWindow); 116 | await driver.switchTo().window(newWindow); 117 | console.log(windows); 118 | await sleep(1000); 119 | firefoxExtensionUrl = driver.getCurrentUrl(); 120 | 121 | // Allow frame permission 122 | await driver.findElement(By.id('frame-perm-btn')).click(); 123 | await mapDriver.firefoxAllowPermission(); 124 | } 125 | } else { 126 | throw Error("Unsupported browser"); 127 | } 128 | } 129 | 130 | async function getIframeCoords() { 131 | const largerMapLink = await driver.wait(until.elementLocated(By.className("google-maps-link"))); 132 | async function impl() { 133 | const href = await largerMapLink.getAttribute("href"); 134 | const linkUrl = new URL(href); 135 | const ll = linkUrl.searchParams.get('ll'); 136 | return ll && ll.split(',', 2).map(Number); 137 | } 138 | return await driver.wait(async () => await impl(), 2000); 139 | } 140 | 141 | async function getIframeZoom() { 142 | const largerMapLink = await driver.wait(until.elementLocated(By.className("google-maps-link"))); 143 | const href = await largerMapLink.getAttribute("href"); 144 | console.log('href', href); 145 | const linkUrl = new URL(href); 146 | return Number(linkUrl.searchParams.get('z')); 147 | } 148 | 149 | async function assertLatLng(expectedLat, expectedLng) { 150 | const [lat, lng] = await getIframeCoords(); 151 | assertIn(lat, expectedLat); 152 | assertIn(lng, expectedLng); 153 | } 154 | 155 | async function setSlider(slider, value) { 156 | await driver.executeScript((slider, value) => { 157 | slider.value = value; 158 | slider.dispatchEvent(new Event('change')) 159 | }, slider, value); 160 | } 161 | }); 162 | -------------------------------------------------------------------------------- /src/inject_everywhere.js: -------------------------------------------------------------------------------- 1 | if (window.SM_INJECT === undefined) { 2 | const DEBUG = chrome.runtime.getManifest().version === '10000'; 3 | window.SM_INJECT = { count: 0 }; 4 | 5 | function _matchAncestor(node, predicate) { 6 | if (predicate(node)) { 7 | return node; 8 | } 9 | if (node.parentNode instanceof Element && node.parentNode !== node) { 10 | return _matchAncestor(node.parentNode, predicate); 11 | } 12 | return null; 13 | } 14 | 15 | class AbstractMapFinder { 16 | static _querySrc(container, tag, possible_substrings) { 17 | for (let elem of container.querySelectorAll(tag)) { 18 | for (let substring of possible_substrings) { 19 | if (elem.src.indexOf(substring) !== -1) { 20 | return true; 21 | } 22 | } 23 | } 24 | return false; 25 | } 26 | 27 | static _findTiledMap(selector, filter) { 28 | let foundImages = Array.from( 29 | document.querySelectorAll(selector)); 30 | // To handle multiple maps on the same page, we make the threshold 31 | // number of images / 4. We consider the common ancestor to be found below 32 | // that threshold. 33 | let foundThreshold = Math.max(foundImages.length / 4, 1); 34 | for (let i = 0; i < 5; i++) { 35 | // Walk maximum 5 levels to find the common ancestor 36 | foundImages = foundImages.map(img => img.parentNode); 37 | const foundSet = new Set(foundImages); 38 | if (foundSet.size <= foundThreshold) { 39 | return Array.from(foundSet) 40 | .map(container => _matchAncestor(container, 41 | node => isVisible(node) 42 | && node.offsetHeight > 1 43 | && node.offsetWidth > 1 44 | && (filter === undefined || filter(node)) 45 | )) 46 | .filter(n => n); 47 | } 48 | } 49 | return []; 50 | 51 | function isVisible(node) { 52 | return window.getComputedStyle(node).display !== "none"; 53 | } 54 | } 55 | } 56 | 57 | class GoogleMapFinder extends AbstractMapFinder { 58 | static _findGmStyleMap() { 59 | return Array.from(document.querySelectorAll('.gm-style:has(img)')) 60 | .filter(container => 61 | this._querySrc(container, 'img', 62 | [ 63 | '//maps.googleapis.com/maps/', 64 | '//www.google.com/maps/', 65 | '//maps.google.com/maps/', 66 | '//maps.gstatic.com/', 67 | ]) 68 | ) 69 | .map(container => container.parentNode); 70 | } 71 | 72 | static _findCanvasMap() { 73 | return Array.from(document.querySelectorAll('.gm-style:has(canvas)')) 74 | .map(container => container.parentNode); 75 | } 76 | 77 | static _findFallbackMap() { 78 | return GoogleMapFinder._findTiledMap('img[src*="//maps.googleapis.com/maps/"]'); 79 | } 80 | 81 | static _findAriaMap() { 82 | if (new URL(location.href).host.indexOf('.google.') > -1) { 83 | return [...document.querySelectorAll('[aria-label=Map]')]; 84 | } else { 85 | return []; 86 | } 87 | } 88 | 89 | static findMaps() { 90 | let mapContainers = GoogleMapFinder._findCanvasMap(); 91 | if (mapContainers.length > 0) { 92 | return mapContainers; 93 | } 94 | 95 | mapContainers = GoogleMapFinder._findGmStyleMap(); 96 | if (mapContainers.length > 0) { 97 | return mapContainers; 98 | } 99 | 100 | mapContainers = GoogleMapFinder._findAriaMap(); 101 | if (mapContainers.length > 0) { 102 | return mapContainers; 103 | } 104 | 105 | mapContainers = GoogleMapFinder._findFallbackMap(); 106 | return mapContainers; 107 | } 108 | } 109 | 110 | // https://developers.arcgis.com/javascript/latest/ 111 | // More examples at https://developers.arcgis.com/javascript/3/jssamples 112 | class ArcGisFinder extends AbstractMapFinder { 113 | static findMaps() { 114 | return [ 115 | ...document.querySelectorAll('.esri-view:has(.esri-view-surface > canvas)'), 116 | // Examples: 117 | // https://developers.arcgis.com/javascript/3/samples/analysis_connectoriginstodestinations/ 118 | // https://www.tsunami.gov/ 119 | ...ArcGisFinder._findTiledMap( 120 | 'img[src*=".arcgisonline.com/"]', 121 | (node) => node.classList.contains("esriMapContainer") && node.getAttribute("id").endsWith("_root")), 122 | ...document.querySelectorAll('.esriMapContainer[id$="_root"]:has(canvas)'), 123 | ]; 124 | } 125 | } 126 | 127 | // https://docs.mapbox.com/ 128 | class MapBoxFinder extends AbstractMapFinder { 129 | static findMaps() { 130 | return [ 131 | ...document.querySelectorAll('.mapboxgl-map:has(canvas.mapboxgl-canvas)'), 132 | ] 133 | .map((elem) => elem.closest('.leaflet-container') || elem); 134 | } 135 | } 136 | 137 | // https://leafletjs.com/ 138 | class LeafletFinder extends AbstractMapFinder { 139 | static findMaps() { 140 | return [ 141 | // https://www.strava.com/activities 142 | ...document.querySelectorAll('.leaflet-container:has(.leaflet-tile-container)') 143 | ]; 144 | } 145 | } 146 | 147 | // https://www.openstreetmap.org/ 148 | class OpenStreetMapFinder extends AbstractMapFinder { 149 | static findMaps() { 150 | return OpenStreetMapFinder._findTiledMap('img[src*="tile.openstreetmap.org"]'); 151 | } 152 | } 153 | 154 | // https://developer.apple.com/documentation/mapkitjs/ 155 | class AppleMapKitFinder extends AbstractMapFinder { 156 | static findMaps() { 157 | return Array.from(document.querySelectorAll('.mk-map-view:has(canvas)')); 158 | } 159 | } 160 | 161 | // https://openlayers.org/ 162 | class OpenLayersMapFinder extends AbstractMapFinder { 163 | static findMaps() { 164 | return Array.from(document.querySelectorAll('.ol-viewport:has(canvas)')); 165 | } 166 | } 167 | 168 | // https://maplibre.org/maplibre-gl-js/docs/, including Azure Maps. 169 | class MapLibreFinder extends AbstractMapFinder { 170 | static findMaps() { 171 | return Array.from(document.querySelectorAll('.maplibregl-map:has(canvas.maplibregl-canvas)')); 172 | } 173 | } 174 | 175 | // https://en.mapy.cz/ 176 | class MapyCzFinder extends AbstractMapFinder { 177 | static findMaps() { 178 | return MapyCzFinder._findTiledMap( 179 | 'img[src*=".mapy.cz/"]', 180 | (node) => node.getAttribute("id") == "map") 181 | } 182 | } 183 | 184 | async function scrollifyExistingMaps() { 185 | const maps = [ 186 | ...GoogleMapFinder.findMaps().map((m) => { return { map: m, type: ScrollableMap.TYPE_GOOGLE_MAPS_API } }), 187 | ...ArcGisFinder.findMaps().map((m) => { return { map: m, type: ScrollableMap.TYPE_ARCGIS } }), 188 | ...MapBoxFinder.findMaps().map((m) => { return { map: m, type: ScrollableMap.TYPE_MAPBOX } }), 189 | ...OpenStreetMapFinder.findMaps().map((m) => { return { map: m, type: ScrollableMap.TYPE_OPEN_STREET_MAP } }), 190 | ...AppleMapKitFinder.findMaps().map((m) => { return { map: m, type: ScrollableMap.TYPE_APPLE_MAPKIT } }), 191 | ...LeafletFinder.findMaps().map((m) => { return { map: m, type: ScrollableMap.TYPE_LEAFLET } }), 192 | ...MapLibreFinder.findMaps().map((m) => { return { map: m, type: ScrollableMap.TYPE_MAPLIBRE } }), 193 | ...OpenLayersMapFinder.findMaps().map((m) => { return { map: m, type: ScrollableMap.TYPE_MAPLIBRE } }), 194 | ...MapyCzFinder.findMaps().map((m) => { return { map: m, type: ScrollableMap.TYPE_MAPYCZ } }), 195 | ]; 196 | if (DEBUG) console.log('Found maps in page?', maps); 197 | if (maps.length <= 0) { 198 | return false; 199 | } 200 | const options = await Pref.getAllOptions(); 201 | for (const { map, type } of maps) { 202 | if (!map.hasAttribute('data-scrollmaps')) { 203 | new ScrollableMap(map, type, SM_INJECT.count++, options); 204 | } else { 205 | if (DEBUG) console.log('Skipping already scrollified map'); 206 | } 207 | } 208 | return true; 209 | } 210 | 211 | function sleep(timeout) { 212 | return new Promise((accept, _) => { setTimeout(accept, timeout); }); 213 | } 214 | 215 | async function poll(func, timeout, count) { 216 | for (let i = 0; i < count; i++) { 217 | if (DEBUG) console.log('Poll scrollify maps', i); 218 | func(); 219 | await sleep(timeout * Math.pow(2, i)); 220 | } 221 | } 222 | 223 | // Init 224 | let lastEventTime = 0; 225 | const THROTTLE_TIME_MS = 2000; 226 | window.addEventListener('wheel', async (e) => { 227 | if (e.timeStamp - lastEventTime > THROTTLE_TIME_MS) { 228 | lastEventTime = e.timeStamp; 229 | if (!_matchAncestor(e.target, (e) => e.hasAttribute('data-scrollmaps'))) { 230 | await scrollifyExistingMaps(); 231 | } 232 | } 233 | }, true); 234 | poll(scrollifyExistingMaps, 2000, 2); 235 | 236 | window.addEventListener('mapsFound', async function (event) { 237 | let map = event.target; 238 | new ScrollableMap(map, event.detail.type, SM_INJECT.count++, await Pref.getAllOptions()); 239 | }, true); 240 | } 241 | -------------------------------------------------------------------------------- /src/background.js: -------------------------------------------------------------------------------- 1 | const DEBUG = chrome.runtime.getManifest().version === '10000'; 2 | 3 | const BADGE_ACTIVE = '\u2713'; 4 | const BADGE_LOADING = '\u21bb'; 5 | const BADGE_DISABLED = '\u2715'; 6 | 7 | const BADGE_COLORS = { 8 | [BADGE_ACTIVE]: '#4CAF50', 9 | [BADGE_LOADING]: '#CDDC39', 10 | [BADGE_DISABLED]: '#BDBDBD' 11 | } 12 | 13 | async function checkErrors(promise, name, expectedErrors = []) { 14 | try { 15 | return await promise; 16 | } catch (e) { 17 | let errorMessage = e ? e.message : undefined; 18 | if (DEBUG && errorMessage) { 19 | for (let expectedError of expectedErrors) { 20 | if (errorMessage.indexOf(expectedError) !== -1) { 21 | console.log(name, errorMessage); 22 | return; 23 | } 24 | } 25 | console.warn(name, errorMessage); 26 | } 27 | } 28 | } 29 | 30 | const INJECT_EXPECTED_ERRORS = [ 31 | 'Cannot access', 32 | 'The extensions gallery cannot be scripted' 33 | ]; 34 | 35 | async function injectScript(tabId, frameId) { 36 | const injectPromises = [ 37 | checkErrors( 38 | chrome.scripting.executeScript({ 39 | target: { 40 | tabId: tabId, 41 | frameIds: frameId === 'all' ? null : [frameId], 42 | allFrames: frameId === 'all', 43 | }, 44 | files: [ 45 | 'inject_everywhere.min.js', 46 | 'inject_frame.min.js', 47 | ], 48 | }), 49 | 'inject scripts', 50 | INJECT_EXPECTED_ERRORS 51 | ), 52 | checkErrors( 53 | chrome.scripting.insertCSS({ 54 | files: ['src/inject_everywhere.css'], 55 | target: { 56 | tabId: tabId, 57 | frameIds: frameId === 'all' ? null : [frameId], 58 | allFrames: frameId === 'all', 59 | }, 60 | }), 61 | 'inject everywhere CSS' 62 | ), 63 | checkErrors( 64 | chrome.scripting.executeScript({ 65 | target: { 66 | 'tabId': tabId, 67 | 'allFrames': true 68 | }, 69 | files: ['scrollability_inject.min.js'], 70 | }), 71 | 'inject scrollability', 72 | INJECT_EXPECTED_ERRORS 73 | ), 74 | ]; 75 | 76 | return Promise.allSettled(injectPromises); 77 | } 78 | 79 | 80 | async function handleBrowserActionClicked(tab) { 81 | if (!Permission.canInjectIntoPage(tab.url)) { 82 | // This extension can't inject into chrome:// pages. Just show the popup 83 | // directly 84 | setBrowserActionBadge(tab.id, BADGE_DISABLED) 85 | return; 86 | } 87 | if (Permission.isOwnExtensionPage(tab.url)) { 88 | // If the permission is required (e.g. if it is on the domain 89 | // google.com), we cannot allow users to toggle the permission. 90 | chrome.tabs.sendMessage(tab.id, { 'action': 'browserActionClicked' }); 91 | return; 92 | } 93 | 94 | chrome.scripting.executeScript({ 95 | func: () => { window.SCROLLMAPS_enabled = true }, 96 | target: { 97 | tabId: tab.id, 98 | allFrames: true 99 | } 100 | }); 101 | await injectScript(tab.id, 'all'); 102 | await registerApiInjection(false); 103 | 104 | if (!await chrome.permissions.contains({ origins: ["*://www.google.com/"] })) { 105 | await checkErrors( 106 | chrome.scripting.executeScript({ 107 | target: { 108 | tabId: tab.id, 109 | allFrames: true, 110 | }, 111 | files: ['inject_frame_permission.min.js'], 112 | }), 113 | 'inject frame permission', 114 | INJECT_EXPECTED_ERRORS 115 | ); 116 | } 117 | 118 | chrome.tabs.sendMessage(tab.id, { 'action': 'browserActionClicked' }); 119 | setBrowserActionBadge(tab.id, BADGE_LOADING); 120 | refreshScrollMapsStatus(tab.id); 121 | setTimeout(async () => { 122 | // Remove the loading badge if no maps responded in 10s 123 | if (await chrome.action.getBadgeText({ tabId: tab.id }) === BADGE_LOADING) { 124 | setBrowserActionBadge(tab.id, ''); 125 | } 126 | }, 10000); 127 | } 128 | 129 | 130 | chrome.action.onClicked.addListener(handleBrowserActionClicked); 131 | 132 | async function refreshScrollMapsStatus(tabId) { 133 | // Check if the map already has a scrollmaps injected (e.g. after extension reloading) 134 | let responses = await checkErrors(chrome.scripting.executeScript({ 135 | target: { 136 | tabId: tabId, 137 | allFrames: true 138 | }, 139 | func: () => !!document.querySelector("[data-scrollmaps='enabled']"), 140 | }), 'map probe', INJECT_EXPECTED_ERRORS); 141 | responses = responses ? responses.map((r) => r && r.result) : []; 142 | if (DEBUG) { 143 | console.log('Map probe responses', tabId, responses); 144 | } 145 | const any = (arr) => { 146 | for (const v of arr || []) { 147 | if (v) return true; 148 | } 149 | return false; 150 | }; 151 | await updateMapStatus(tabId, any(responses)); 152 | } 153 | 154 | async function updateMapStatus(tabId, mapEnabled) { 155 | if (mapEnabled) { 156 | setBrowserActionBadge(tabId, BADGE_ACTIVE); 157 | } else { 158 | if (await chrome.action.getBadgeText({ tabId: tabId }) === BADGE_ACTIVE) { 159 | setBrowserActionBadge(tabId, ''); 160 | } 161 | } 162 | } 163 | 164 | function updateAllTabs() { 165 | chrome.tabs.query({}, (tabs) => { 166 | for (let tab of tabs) { 167 | refreshScrollMapsStatus(tab.id); 168 | } 169 | }); 170 | } 171 | 172 | updateAllTabs(); 173 | 174 | Pref.initBackgroundPage(); 175 | 176 | async function registerApiInjection(init) { 177 | try { 178 | let func = init ? chrome.scripting.registerContentScripts : chrome.scripting.updateContentScripts; 179 | await func([ 180 | { 181 | id: 'inject_everywhere', 182 | allFrames: true, 183 | matches: [''], 184 | js: ['inject_everywhere.min.js'], 185 | css: ['src/inject_everywhere.css'] 186 | } 187 | ]); 188 | } catch (e) { 189 | console.error(e); 190 | } 191 | } 192 | 193 | registerApiInjection(true); 194 | chrome.tabs.onUpdated.addListener((tabId, changeInfo) => { 195 | if (changeInfo.status === 'loading' || changeInfo.status === 'complete') { 196 | injectScript(tabId, 'all'); 197 | 198 | // For single-page applications, if the loading state changed, check if 199 | // a scrollmap element is still present if the tab is "updated". 200 | // TODO: Maybe use chrome.tabs.connect for more robust status monitoring 201 | refreshScrollMapsStatus(tabId); 202 | } 203 | }); 204 | 205 | 206 | function setBrowserActionBadge(tabId, badge) { 207 | chrome.action.setBadgeText({ 'text': badge, 'tabId': tabId }); 208 | if (badge !== '') { 209 | chrome.action.setBadgeBackgroundColor( 210 | { 'color': BADGE_COLORS[badge], 'tabId': tabId }); 211 | } 212 | chrome.action.setPopup({ 213 | 'tabId': tabId, 214 | 'popup': badge !== '' ? chrome.runtime.getURL('src/popup/popup.html') : '', 215 | }); 216 | } 217 | 218 | function sleep(time) { 219 | return new Promise((accept, _) => { setTimeout(accept, time); }); 220 | } 221 | 222 | async function requestFramePermission(tabId) { 223 | let granted = await requestFramePermissionImpl(tabId); 224 | if (granted) { 225 | framePermissionGranted(tabId); 226 | } 227 | return granted; 228 | } 229 | 230 | async function requestFramePermissionImpl(tabId) { 231 | try { 232 | return await Permission.requestFramePermission(); 233 | } catch (e) { 234 | // On Firefox background scripts cannot request permissions because the "user gesture" is not propagated through 235 | // chrome.runtime.sendMessage: https://bugzilla.mozilla.org/show_bug.cgi?id=1392624 236 | // Create a page to ask the user about it instead. 237 | console.log('error requesting permission', e); 238 | let tab = await chrome.tabs.create({ openerTabId: tabId, url: chrome.runtime.getURL(`src/options/framepermission.html?id=${tabId}`) }); 239 | for (let i = 0; i < 5; i++) { 240 | try { 241 | return await chrome.tabs.sendMessage(tab.id, { 'action': 'waitForPermission' }); 242 | } catch (e) { 243 | console.log('waitForPermission error', e, 'retrying...') 244 | await sleep(1000); 245 | } 246 | } 247 | return false; 248 | } 249 | } 250 | 251 | function framePermissionGranted(tabId) { 252 | injectScript(tabId, 'all').then((r) => console.log(r)); 253 | } 254 | 255 | async function injectMainScript(sender) { 256 | return await checkErrors( 257 | chrome.scripting.executeScript({ 258 | target: { 259 | tabId: sender.tab.id, 260 | frameIds: [sender.frameId], 261 | }, 262 | files: [ 263 | 'inject_main.min.js', 264 | ], 265 | world: "MAIN", 266 | }), 267 | 'inject main script', 268 | INJECT_EXPECTED_ERRORS 269 | ); 270 | } 271 | 272 | 273 | chrome.runtime.onMessage.addListener( 274 | (request, sender, sendResponse) => { 275 | if (request.action === 'mapLoaded') { 276 | if (DEBUG) console.log('mapLoaded', sender.tab); 277 | console.log(sender.tab.url, chrome.runtime.getURL('src/options/options.html')) 278 | if (sender.tab) { 279 | if (sender.tab.url == chrome.runtime.getURL('src/options/options.html')) { 280 | // Cannot inject script into extension page. Just trust the result from our 281 | // options page 282 | updateMapStatus(sender.tab.id, true); 283 | } else { 284 | refreshScrollMapsStatus(sender.tab.id); 285 | } 286 | injectMainScript(sender); 287 | } else { 288 | console.warn('mapLoaded sent without tab', sender); 289 | } 290 | } else if (request.action === 'mapUnloaded') { 291 | if (DEBUG) console.log('mapUnloaded', sender.tab); 292 | if (sender.tab) { 293 | if (sender.tab.url == chrome.runtime.getURL('src/options/options.html')) { 294 | // Cannot inject script into extension page. Just trust the result from our 295 | // options page 296 | updateMapStatus(sender.tab.id, false); 297 | } else { 298 | refreshScrollMapsStatus(sender.tab.id); 299 | } 300 | } else { 301 | console.warn('mapUnloaded sent without tab', sender); 302 | } 303 | } else if (request.action === 'popupLoaded') { 304 | chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => { 305 | for (const tab of tabs) { 306 | handleBrowserActionClicked(tab); 307 | } 308 | }); 309 | } else if (request.action === 'requestIframePermission') { 310 | requestFramePermission(sender.tab.id).then(sendResponse); 311 | return true; 312 | } else if (request.action === 'framePermissionGranted') { 313 | framePermissionGranted(request.tabId || sender.tab.id); 314 | } 315 | }); 316 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /test/mapdriver.js: -------------------------------------------------------------------------------- 1 | const webdriver = require('selenium-webdriver'); 2 | const process = require('process'); 3 | const child_process = require('child_process'); 4 | const util = require('util'); 5 | const exec = util.promisify(child_process.exec); 6 | const portprober = require('selenium-webdriver/net/portprober'); 7 | const assert = require('assert'); 8 | 9 | let chrome, firefox, edge; 10 | if (process.env.BROWSER === 'chrome') { 11 | chrome = require('selenium-webdriver/chrome'); 12 | require('chromedriver'); 13 | } else if (process.env.BROWSER === 'firefox') { 14 | firefox = require('selenium-webdriver/firefox'); 15 | require('geckodriver'); 16 | } else if (process.env.BROWSER === 'edge') { 17 | edge = require('selenium-webdriver/edge'); 18 | edge.driverModule = require('ms-chromium-edge-driver'); 19 | } 20 | 21 | const By = webdriver.By; 22 | 23 | 24 | class MapDriver { 25 | static async create() { 26 | let driver; 27 | let port = await portprober.findFreePort(); 28 | const extras = {}; 29 | if (process.env.BROWSER === 'chrome') { 30 | driver = new webdriver.Builder() 31 | .forBrowser('chrome') 32 | .setChromeService(new chrome.ServiceBuilder().setPort(port)) 33 | .setChromeOptions( 34 | new chrome.Options() 35 | .addArguments(`load-extension=${process.cwd()}/gen/plugin-10000-chrome`, 'window-size=800,600') 36 | .addArguments(`disable-features=SidePanelPinning`) 37 | ) 38 | .build(); 39 | } else if (process.env.BROWSER === 'edge') { 40 | const edgePaths = await edge.driverModule.installDriver(); 41 | driver = new webdriver.Builder() 42 | .forBrowser('MicrosoftEdge') 43 | .setEdgeOptions( 44 | new edge.Options() 45 | .addArguments( 46 | `load-extension=${process.cwd()}/gen/plugin-10000-edge`, 47 | 'window-size=800,600', 48 | ) 49 | // Avoid "Personalize your web experience" prompt 50 | // https://stackoverflow.com/a/77626549/2921519 51 | .setUserPreferences({"user_experience_metrics.personalization_data_consent_enabled": true}) 52 | ) 53 | .setEdgeService( 54 | new edge.ServiceBuilder(edgePaths.driverPath) 55 | .setPort(port) 56 | ) 57 | .build(); 58 | } else if (process.env.BROWSER === 'firefox') { 59 | driver = new webdriver.Builder() 60 | .forBrowser('firefox') 61 | .setFirefoxService(new firefox.ServiceBuilder().setPort(port)) 62 | .setFirefoxOptions( 63 | new firefox.Options() 64 | .windowSize({width: 800, height: 600}) 65 | ) 66 | .build(); 67 | extras.extensionId = await driver.installAddon(`${process.cwd()}/gen/scrollmaps-10000-firefox.zip`, true); 68 | console.log("Installed extension ", extras.extensionId); 69 | } else { 70 | throw new Error('Environment variable $BROWSER not defined'); 71 | } 72 | const mapDriver = new MapDriver(driver, port); 73 | mapDriver.extras = extras; 74 | try { 75 | let currentSize = [800, 600]; 76 | // Make sure the browser height is normalized 77 | await driver.wait(async () => { 78 | const innerSize = await driver.executeScript(() => [window.innerWidth, window.innerHeight]); 79 | const sizeDiff = [innerSize[0] - 800, innerSize[1] - 600]; 80 | if (sizeDiff[0] === 0 && sizeDiff[1] === 0) { 81 | return true; 82 | } 83 | currentSize = [currentSize[0] - sizeDiff[0], currentSize[1] - sizeDiff[1]]; 84 | console.log('Tweaking window size to be 800x600. Current=', currentSize); 85 | await driver.manage().window().setRect({width: currentSize[0], height: currentSize[1]}); 86 | return false; 87 | }); 88 | console.log("Size tweak complete") 89 | } catch (e) { 90 | await mapDriver.quit(); 91 | throw e; 92 | } 93 | return mapDriver; 94 | } 95 | 96 | constructor(driver, port) { 97 | this.driver = driver; 98 | this.port = port; 99 | } 100 | 101 | async quit() { 102 | await this.driver.quit(); 103 | } 104 | 105 | async waitForScrollMapsLoaded(timeout = 10000) { 106 | console.log("Waiting for scrollmaps to load"); 107 | // ScrollMaps should be activated automatically 108 | const elem = await this.driver.wait(async () => { 109 | return (await this.driver.findElements(By.css('[data-scrollmaps]')))[0]; 110 | }, timeout); 111 | // console.log('elem', elem) 112 | await this.driver.wait( 113 | async () => await elem.getAttribute('data-scrollmaps') === 'enabled', 114 | timeout, 115 | "Unable to wait for [data-scrollmaps] element" 116 | ); 117 | return elem; 118 | } 119 | 120 | async activateAndWaitForScrollMapsLoaded() { 121 | try { 122 | return await this.waitForScrollMapsLoaded(1000); 123 | } catch (e) { 124 | await this.clickBrowserAction(); 125 | return await this.waitForScrollMapsLoaded(); 126 | } 127 | } 128 | 129 | async activateForGoogleDomain() { 130 | if (process.env.BROWSER === 'firefox') { 131 | await this.clickBrowserAction(); 132 | } 133 | // For Chrome and Edge, Google domains are part of the required permissions and granted 134 | // during installation. 135 | } 136 | 137 | async waitForCanvasMapsLoaded(contextType) { 138 | // The webGL mode of maps takes a while to load 139 | const elem = await this.waitForScrollMapsLoaded(); 140 | const r = await elem.getRect(); 141 | await this.driver.wait(async () => { 142 | return await this.driver.executeScript((r, contextType) => { 143 | const clientX = r.x + r.width / 2; 144 | const clientY = r.y + r.height / 2; 145 | const pointElem = document.elementFromPoint(clientX, clientY); 146 | console.log('pointElem', pointElem); 147 | return pointElem instanceof HTMLCanvasElement && !!pointElem.getContext(contextType); 148 | }, r, contextType); 149 | }, 10000, "Unable to wait for canvas map"); 150 | return elem; 151 | } 152 | 153 | async pinchGesture(elem, deltaY, opts = {}) { 154 | // Firefox tends to have lower deltaY than Chromium browsers for pinch gestures 155 | // const browserScale = firefox ? 0.5 : 1; 156 | return await this.scroll(elem, 0, deltaY, { 157 | ctrlKey: true, 158 | logTag: 'Zooming', 159 | // browserScale: browserScale, 160 | ...opts 161 | }) 162 | } 163 | 164 | async pinchUntil(elem, deltaY, until, opts = {maxTries: 10}) { 165 | for (let i = 0; i < opts.maxTries; i++) { 166 | await this.scroll(elem, 0, deltaY, { 167 | ctrlKey: true, 168 | logTag: 'Zooming', 169 | // browserScale: browserScale, 170 | ...opts 171 | }); 172 | if (await until()) { 173 | return i; 174 | } 175 | await sleep(500); 176 | } 177 | throw Error("Unable to meet pinch until criteria"); 178 | } 179 | 180 | async scrollIntoView(elem) { 181 | await this.driver.executeScript((elem) => elem.scrollIntoView(), elem); 182 | } 183 | 184 | async scroll(elem, dx, dy, {logTag = 'Scrolling', ...opts} = {}) { 185 | const r = await elem.getRect(); 186 | console.log(`${logTag} map by (${dx}, ${dy})`); 187 | await this.driver.executeAsyncScript(async (elem, r, dx, dy, opts, done) => { 188 | try { 189 | console.log('dy', dy); 190 | const clientX = r.x + r.width / 2 - document.documentElement.scrollLeft; 191 | const clientY = r.y + r.height / 2 - document.documentElement.scrollTop; 192 | const pointElem = document.elementFromPoint(clientX, clientY); 193 | if (pointElem === null) { 194 | done(new Error('pointElem is null')); 195 | } 196 | console.log('pointElem', elem, pointElem); 197 | const sleep = (t) => new Promise((resolve, reject) => setTimeout(resolve, t)); 198 | const wheel = (dx, dy) => { 199 | console.log('Dispatching wheel event', dx, dy, opts.ctrlKey); 200 | pointElem.dispatchEvent(new WheelEvent('wheel', { 201 | view: window, 202 | bubbles: true, 203 | cancelable: true, 204 | clientX: clientX, 205 | clientY: clientY, 206 | deltaX: dx, 207 | deltaY: dy, 208 | ...opts 209 | })); 210 | }; 211 | const chunks = Math.round(Math.max(Math.abs(dx) / 16, Math.abs(dy) / 16)); 212 | const browserScale = opts.browserScale || 1; 213 | for (let i = 0; i < chunks; i++) { 214 | wheel(dx / chunks * browserScale, dy / chunks * browserScale); 215 | await sleep(30); 216 | } 217 | } finally { 218 | done(); 219 | } 220 | }, elem, r, dx, dy, opts); 221 | } 222 | 223 | async click({x = 100, y = 100} = {}) { 224 | const elem = await this.waitForScrollMapsLoaded(); 225 | console.log(`Click map at (${x}, ${y})`); 226 | await this.driver.actions({ bridge: true }) 227 | .move({ origin: elem, x: x, y: y, duration: 0 }) 228 | .click() 229 | .perform(); 230 | } 231 | 232 | async firefoxAllowPermission() { 233 | const firefox = await import('selenium-webdriver/firefox.js'); 234 | this.driver.setContext(firefox.Context.CHROME); 235 | const allowPermBtn = await this.driver.wait(async () => { 236 | // await mapDriver.printAllElements(); 237 | // Reference: 238 | // https://searchfox.org/mozilla-central/source/toolkit/modules/PopupNotifications.sys.mjs 239 | // https://searchfox.org/mozilla-central/source/toolkit/content/widgets/popupnotification.js 240 | return (await this.driver.findElement(By.css('#addon-webext-permissions-notification .popup-notification-primary-button'))); 241 | }, 5000, "Unable to find allow permission button in the Firefox browser chrome"); 242 | await allowPermBtn.click(); 243 | this.driver.setContext(firefox.Context.CONTENT); 244 | } 245 | 246 | /** 247 | * Check against the ruler at the bottom to see if the zoom level is roughly as expected. 248 | */ 249 | async assertRuler(expectedKm) { 250 | const elem = await this.waitForScrollMapsLoaded(); 251 | const km = await this.driver.wait(async () => 252 | elem.findElement(By.xpath('//*[@class="gm-style-cc"]//*[contains(text(), "km")]')), 10000, 253 | "Unable to find Google Maps ruler"); 254 | const kmText = await km.getText(); 255 | assert.equal(kmText.trim(), expectedKm); 256 | } 257 | 258 | async printAllElements(root) { 259 | root = root || this.driver; 260 | for (const elem of await root.findElements(By.xpath("//*"))) { 261 | const id = await elem.getAttribute("id"); 262 | if (id) console.log("Element ID=", id); 263 | const classes = await elem.getAttribute("class"); 264 | if (classes) console.log("Element classes=", classes); 265 | } 266 | } 267 | 268 | async clickBrowserAction() { 269 | if (process.env.BROWSER === 'firefox') { 270 | this.driver.setContext(firefox.Context.CHROME); 271 | const extensionsButton = await this.driver.wait(async () => { 272 | return await this.driver.findElement(By.id("unified-extensions-button")); 273 | }, 10000, "Unable to find firefox unified extension button"); 274 | await extensionsButton.click(); 275 | const browserAction = await this.driver.wait(async () => { 276 | // await this.printAllElements(); 277 | const extensionButtonId = this.extras.extensionId.replace('@', '_') + '-BAP'; 278 | return (await this.driver.findElement(By.id(extensionButtonId))); 279 | }, 10000, "Unable to find ScrollMaps browser action button"); 280 | await browserAction.click(); 281 | this.driver.setContext(firefox.Context.CONTENT); 282 | } else { 283 | // Run the applescript for Chromium based browsers 284 | // First, find out who is using the driver port (which should be this node process, and the driver) 285 | const psresult = await exec(`lsof -t -i tcp:${this.port}`); 286 | const driverPid = psresult.stdout.trim().split('\n') 287 | .map(Number).filter(pid => pid && pid != process.pid); 288 | // console.log('Driver PID:', driverPid); 289 | const pgrepResult = await exec(`pgrep -P "${driverPid}"`); 290 | const childPid = parseInt(pgrepResult.stdout.trim()); 291 | console.log(`Clicking browser action on process ${childPid}`); 292 | await exec(`test/chrome_browser_action.js`, 293 | { 294 | env: {'TEST_PROCESS': childPid, 'BROWSER': process.env.BROWSER}, 295 | stdio: [process.stdin, process.stdout, process.stderr], 296 | }); 297 | } 298 | } 299 | } 300 | 301 | function sleep(timeout) { 302 | return new Promise((resolve, reject) => setTimeout(resolve, timeout)); 303 | } 304 | 305 | function assertIn(value, [expected, tolerance], opts = { message: `${value} not within ${expected} +- ${tolerance}` }) { 306 | assert(expected - tolerance <= value && value <= expected + tolerance, opts.message) 307 | } 308 | 309 | exports.MapDriver = MapDriver; 310 | exports.sleep = sleep; 311 | exports.assertIn = assertIn; 312 | -------------------------------------------------------------------------------- /gulpfile.mjs: -------------------------------------------------------------------------------- 1 | import gulp from 'gulp'; 2 | const { src, dest, series, parallel } = gulp; 3 | import concat from 'gulp-concat'; 4 | import { deleteAsync, deleteSync } from 'del'; 5 | import rename from 'gulp-rename'; 6 | import zip from 'gulp-zip'; 7 | import mocha from 'gulp-mocha'; 8 | import { promises as fs } from 'fs'; 9 | import open from 'open'; 10 | import { makePromise, runParallel, runSeries, contentTransform, execTask } from './gulputils.mjs'; 11 | import newer from 'gulp-newer'; 12 | import minimist from 'minimist'; 13 | import karma from 'karma'; 14 | import { fileURLToPath } from 'url'; 15 | const __filename = fileURLToPath(import.meta.url); 16 | 17 | 18 | const BROWSERS = ['chrome', 'firefox', 'edge']; 19 | const BROWSER_FLAGS = {}; 20 | for (const browser of BROWSERS) { 21 | BROWSER_FLAGS[`--${browser}`] = `for [${browser}] browser`; 22 | } 23 | 24 | function doubleInclusionGuard() { 25 | return contentTransform((contents, file, enc) => 26 | `if (!self["..SMLoaded:${file.basename}"]) { 27 | ${contents}; 28 | self["..SMLoaded:${file.basename}"]=true; 29 | }`); 30 | } 31 | 32 | class BuildContext { 33 | 34 | constructor(browser, version) { 35 | if (!browser) throw new Error('Browser is not defined'); 36 | if (!version) throw new Error('Version is not defined'); 37 | this.browser = browser; 38 | this.version = version; 39 | 40 | // Bind all the functions of this instance 41 | for (const prop of Object.getOwnPropertyNames(BuildContext.prototype)) { 42 | if (this[prop] instanceof Function) { 43 | this[prop] = this[prop].bind(this); 44 | this[prop].displayName = `[${browser}] ${this[prop].name}`; 45 | } 46 | } 47 | } 48 | 49 | intermediatesDir() { return `gen/intermediates-${this.version}-${this.browser}` } 50 | pluginDir() { return `gen/plugin-${this.version}-${this.browser}`; } 51 | 52 | // ===== Tasks ===== 53 | 54 | copySourceFiles() { 55 | return src([ 56 | 'src/**/*.js', 57 | 'src/**/*.mjs', 58 | 'src/**/*.css', 59 | 'src/**/*.html', 60 | '!src/inject_frame.js', 61 | '!src/inject_frame_permission.js', 62 | '!src/inject_everywhere.js', 63 | '!src/options/maps_embed.mjs', 64 | '!src/options/maps_embed_with_key.mjs', 65 | ]) 66 | .pipe(newer(`${this.pluginDir()}/src`)) 67 | .pipe(dest(`${this.pluginDir()}/src`)); 68 | } 69 | 70 | async copyMapsEmbedFile() { 71 | let mapsEmbedFile; 72 | try { 73 | await fs.access('src/options/maps_embed_with_key.mjs'); 74 | mapsEmbedFile = 'src/options/maps_embed_with_key.mjs'; 75 | } catch (e) { 76 | mapsEmbedFile = 'src/options/maps_embed.mjs'; 77 | } 78 | return src([mapsEmbedFile]) 79 | .pipe(rename('options/maps_embed.mjs')) 80 | .pipe(newer(`${this.pluginDir()}/src`)) 81 | .pipe(dest(`${this.pluginDir()}/src`)); 82 | } 83 | 84 | copyImages() { 85 | return src(['images/**/*.png'], { encoding: false }) 86 | .pipe(newer(`${this.pluginDir()}/images`)) 87 | .pipe(dest(`${this.pluginDir()}/images`)) 88 | } 89 | 90 | processManifest() { 91 | return src(this.browser === 'firefox' ? 'manifest_template.json' : 'manifest_chrome_template.json') 92 | .pipe(newer({ dest: `${this.pluginDir()}/manifest.json`, extra: __filename })) 93 | .pipe(contentTransform(this._processManifestTemplate)) 94 | .pipe(rename('manifest.json')) 95 | .pipe(dest(this.pluginDir())); 96 | } 97 | 98 | async generateDomainDotJs() { 99 | const urls = this._getGoogleMapUrls(); 100 | await fs.mkdir(`${this.pluginDir()}/src`, { recursive: true }); 101 | await fs.writeFile( 102 | `${this.pluginDir()}/src/domains.js`, 103 | 'const SCROLLMAPS_DOMAINS = ' + JSON.stringify(urls)); 104 | } 105 | 106 | _processManifestTemplate(content) { 107 | let manifest = JSON.parse(content); 108 | let processObj = (obj) => { 109 | if (Array.isArray(obj)) { 110 | let index = obj.indexOf('<%= all_google_maps_urls %>'); 111 | if (index !== -1) { 112 | obj.splice(index, 1, ...this._getGoogleMapUrls()); 113 | } 114 | } 115 | if (typeof obj === 'object') { 116 | for (let o in obj) { 117 | if (typeof obj[o] === 'object') { 118 | processObj(obj[o]); 119 | } 120 | } 121 | if (this.browser === 'chrome') { 122 | if (obj && obj.browser_specific_settings && obj.browser_specific_settings.chrome) { 123 | const chromeSettings = obj.browser_specific_settings.chrome; 124 | if (chromeSettings) { 125 | for (const i in chromeSettings) { 126 | obj[i] = chromeSettings[i]; 127 | } 128 | delete obj.browser_specific_settings; 129 | } 130 | } 131 | } 132 | } 133 | } 134 | processObj(manifest); 135 | manifest.version = '' + this.version; 136 | return JSON.stringify(manifest, null, ' '); 137 | } 138 | 139 | _getGoogleMapUrls() { 140 | const GOOGLE_MAPS_CCTLDS = [ 141 | "at", "au", "be", "br", "ca", "cf", "cg", "ch", "ci", "cl", "cn", "uk", "in", "jp", "th", 142 | "cz", "dj", "de", "dk", "ee", "es", "fi", "fr", "ga", "gm", "hk", "hr", "hu", "ie", "is", 143 | "it", "li", "lt", "lu", "lv", "mg", "mk", "mu", "mw", "nl", "no", "nz", "pl", "pt", "ro", 144 | "ru", "rw", "sc", "se", "sg", "si", "sk", "sn", "st", "td", "tg", "tr", "tw", "ua", "us"]; 145 | 146 | const GOOGLE_MAPS_URL_FORMATS = [ 147 | "*://www.google.{tld}/maps*", 148 | "*://www.google.com.{tld}/maps*", 149 | "*://www.google.co.{tld}/maps*", 150 | "*://maps.google.{tld}/*", 151 | "*://maps.google.com.{tld}/*", 152 | "*://maps.google.co.{tld}/*" 153 | ]; 154 | 155 | const GOOGLE_MAPS_SPECIAL_URLS = [ 156 | "*://www.google.com/maps*", 157 | "*://maps.google.com/*", 158 | "*://mapy.google.pl/*", 159 | "*://ditu.google.cn/*" 160 | ]; 161 | 162 | 163 | const output = [...GOOGLE_MAPS_SPECIAL_URLS]; 164 | for (const tld of GOOGLE_MAPS_CCTLDS) { 165 | for (const format of GOOGLE_MAPS_URL_FORMATS) { 166 | output.push(format.replace('{tld}', tld)); 167 | } 168 | } 169 | return output; 170 | } 171 | 172 | MINIFY_FILES() { 173 | return { 174 | 'inject_everywhere': [ 175 | "src/pref.js", 176 | "src/Scrollability.js", 177 | "src/ScrollableMap.js", 178 | "src/inject_everywhere.js" 179 | ], 180 | 'inject_frame_permission': [ 181 | "src/inject_frame_permission.js", 182 | ], 183 | 'scrollability_inject': ["src/Scrollability.js"], 184 | 'inject_frame': [ 185 | "src/pref.js", 186 | "src/Scrollability.js", 187 | "src/ScrollableMap.js", 188 | "src/permission.js", 189 | `${this.pluginDir()}/src/domains.js`, 190 | "src/inject_frame.js" 191 | ], 192 | 'inject_main': [ 193 | "src/inject_main.js", 194 | ], 195 | 'background': [ 196 | "src/pref.js", 197 | "src/permission.js", 198 | "src/background.js", 199 | `${this.pluginDir()}/src/domains.js`, 200 | ], 201 | } 202 | } 203 | 204 | zipExtension() { 205 | return src([this.pluginDir() + '/**'], { encoding: false }) 206 | .pipe(newer(`gen/scrollmaps-${this.version}-${this.browser}.zip`)) 207 | .pipe(zip(`scrollmaps-${this.version}-${this.browser}.zip`)) 208 | .pipe(dest('gen')); 209 | } 210 | 211 | async build() { 212 | const minifyTasks = Object.entries(this.MINIFY_FILES()).map(([output, sourceFiles]) => { 213 | const minifyTask = () => 214 | src(sourceFiles) 215 | .pipe(newer({ dest: `${this.pluginDir()}/${output}.min.js`, extra: __filename })) 216 | .pipe(concat(`${output}.min.js`)) 217 | .pipe(doubleInclusionGuard()) 218 | .pipe(dest(this.pluginDir())); 219 | minifyTask.displayName = `[${this.browser}] minify_${output}` 220 | return minifyTask; 221 | }); 222 | const buildUnpacked = parallel( 223 | ...minifyTasks, 224 | this.copySourceFiles, 225 | this.copyMapsEmbedFile, 226 | this.copyImages, 227 | this.processManifest, 228 | ); 229 | if (this.browser === 'firefox') { 230 | return runSeries(this.generateDomainDotJs, buildUnpacked, this.zipExtension); 231 | } else { 232 | return runSeries(this.generateDomainDotJs, buildUnpacked); 233 | } 234 | } 235 | 236 | // ===== Test tasks ===== 237 | 238 | async _generateTestJson() { 239 | // Install a mocha hook that writes to process.env.BROWSER. 240 | // This is to work around the fact that gulp-mocha does not 241 | // have a way to set process env variables per process, and 242 | // setting it globally in the current process breaks parallel 243 | // test runs. 244 | await fs.mkdir(this.intermediatesDir(), { recursive: true }); 245 | await fs.writeFile( 246 | `${this.intermediatesDir()}/mocha-require-${this.browser}.mjs`, 247 | `export const mochaHooks = () => { process.env.BROWSER = "${this.browser}" }`) 248 | } 249 | 250 | async runAutoTest() { 251 | await this._generateTestJson(); 252 | await makePromise( 253 | () => src('test/auto/*.mjs') 254 | .pipe(mocha({ 255 | require: [`${this.intermediatesDir()}/mocha-require-${this.browser}.mjs`], 256 | reporter: 'spec', 257 | timeout: 100000 258 | })) 259 | ); 260 | } 261 | 262 | async runManualTest() { 263 | await this._generateTestJson(); 264 | await makePromise( 265 | () => src('test/manual/*.js') 266 | .pipe(mocha({ 267 | require: [`${this.intermediatesDir()}/mocha-require-${this.browser}.mjs`], 268 | reporter: 'spec', 269 | timeout: 100000 270 | })) 271 | ); 272 | } 273 | 274 | runUnitTest(watch = false) { 275 | const task = async (done) => { 276 | let config = await karma.config.parseConfig(null, { 277 | frameworks: ['mocha', 'chai'], 278 | files: [ 279 | 'test/unit/fakes.js', 280 | `${this.pluginDir()}/src/domains.js`, 281 | `${this.pluginDir()}/src/permission.js`, 282 | `${this.pluginDir()}/src/Scrollability.js`, 283 | 'test/unit/permission_test.js', 284 | 'test/unit/Scrollability_test.js' 285 | ], 286 | singleRun: !watch, 287 | browsers: ['ChromeHeadless'], 288 | }); 289 | new karma.Server(config, done).start(); 290 | }; 291 | task.displayName = `[${this.browser}] runUnitTest`; 292 | return task; 293 | } 294 | 295 | // ===== Release tasks ===== 296 | 297 | async openStoreLink() { 298 | switch (this.browser) { 299 | case 'chrome': 300 | await open('https://chrome.google.com/webstore/developer/edit/jifommjndpnefcfplgnbhabocomgdjjg'); 301 | break; 302 | case 'edge': 303 | await open('https://partner.microsoft.com/en-us/dashboard/microsoftedge/27ae3b1c-3f31-477b-b8e3-bddb29477f74/packages'); 304 | break; 305 | case 'firefox': 306 | await open('https://addons.mozilla.org/en-US/developers/addon/scrollmaps/ownership'); 307 | break; 308 | default: 309 | throw new Error(`Unsupported browser ${this.browser}`) 310 | } 311 | } 312 | } 313 | 314 | export async function testall() { 315 | const tasks = BROWSERS.map((browser) => { 316 | const bc = new BuildContext(browser, 10000); 317 | return series(bc.build, bc.runAutoTest); 318 | }); 319 | // Cannot run in parallel because Applescript (used to trigger browser 320 | // action) requires window focus 321 | return runSeries(...tasks); 322 | } 323 | testall.description = 'Run tests for all browsers'; 324 | 325 | export async function test() { 326 | const bc = new BuildContext(getBrowser(), 10000); 327 | return runSeries(bc.build, bc.runAutoTest); 328 | } 329 | test.description = 'Run tests for a particular browser'; 330 | test.flags = BROWSER_FLAGS; 331 | 332 | async function devBuild() { 333 | return new BuildContext(getBrowser(), 10000).build(); 334 | } 335 | devBuild.description = 'Build the development version of the browser'; 336 | devBuild.flags = BROWSER_FLAGS; 337 | 338 | async function releaseBuild() { 339 | const packageJsonString = await fs.readFile('package.json'); 340 | const packageJson = JSON.parse(packageJsonString); 341 | if (!packageJson.version) { 342 | throw new Error('Cannot get version from package.json') 343 | } 344 | const tasks = BROWSERS 345 | .map((browser) => new BuildContext(browser, packageJson.version)) 346 | .map((bc) => series(bc.build, bc.zipExtension)); 347 | await runParallel(...tasks); 348 | } 349 | releaseBuild.description = 'Build for all releases'; 350 | 351 | 352 | // Task to be run after running `npm version [major/minor]` 353 | export async function postVersion() { 354 | const packageJsonString = await fs.readFile('package.json'); 355 | const packageJson = JSON.parse(packageJsonString); 356 | if (!packageJson.version) { 357 | throw new Error('Cannot get version from package.json') 358 | } 359 | const tasks = BROWSERS 360 | .map((browser) => new BuildContext(browser, packageJson.version)) 361 | .map((bc) => series(bc.build, bc.zipExtension)); 362 | await runSeries( 363 | parallel(...tasks), 364 | parallel( 365 | execTask('git push'), 366 | async () => open('gen'), 367 | ), 368 | async () => open(`https://github.com/mauricelam/ScrollMaps/releases/new?tag=v${packageJson.version}`), 369 | ); 370 | } 371 | postVersion.description = 'Do not call directly. Use `npm version ` instead.' 372 | 373 | function watchDevBuild() { 374 | gulp.watch( 375 | [ 376 | 'src/**', 377 | 'gulputils.js', 378 | 'manifest_template.json', 379 | 'manifest_chrome_template.json', 380 | 'images/*', 381 | __filename, 382 | ], 383 | { events: 'all', ignoreInitial: false }, 384 | devBuild 385 | ) 386 | } 387 | watchDevBuild.description = 'Watch for changes in source files and build development builds'; 388 | 389 | async function runUnitTest() { 390 | const bc = new BuildContext('chrome', 10000); 391 | await runSeries( 392 | bc.build, 393 | bc.runUnitTest(), 394 | ); 395 | } 396 | runUnitTest.description = 'Run unit tests in a headless chrome instance'; 397 | 398 | async function watchUnitTest() { 399 | const bc = new BuildContext('chrome', 10000); 400 | gulp.watch( 401 | [ 402 | 'src/**', 403 | 'gulputils.js', 404 | 'manifest_template.json', 405 | 'manifest_chrome_template.json', 406 | 'images/*', 407 | __filename, 408 | ], 409 | { events: 'all' }, 410 | bc.build 411 | ); 412 | await runSeries( 413 | bc.build, 414 | bc.runUnitTest(true), 415 | ); 416 | } 417 | watchUnitTest.description = 'Watch for file changes and automatically run unit tests'; 418 | 419 | export async function publish() { 420 | const bc = new BuildContext(getBrowser(), 10000); 421 | await bc.openStoreLink(); 422 | } 423 | 424 | export async function clean() { 425 | return await deleteAsync(['gen/*']); 426 | } 427 | clean.description = 'Remove all build outputs'; 428 | 429 | // Allow --chrome, --firefox, --edge as command line args 430 | function getBrowser() { 431 | const args = minimist(process.argv.slice(1)); 432 | for (const browser of BROWSERS) { 433 | if (args[browser]) { 434 | process.env.BROWSER = browser; 435 | } 436 | } 437 | if (!process.env.BROWSER) { 438 | throw new Error('Browser must be specified with --chrome, --firefox, or --edge'); 439 | } 440 | return process.env.BROWSER; 441 | } 442 | 443 | export default devBuild; 444 | export const dev = devBuild; 445 | export const release = releaseBuild; 446 | export const unit = runUnitTest; 447 | export const watchunit = watchUnitTest; 448 | export const watch = watchDevBuild; 449 | -------------------------------------------------------------------------------- /src/ScrollableMap.js: -------------------------------------------------------------------------------- 1 | if (window.ScrollableMap === undefined) { 2 | const DEBUG = chrome.runtime.getManifest().version === '10000'; 3 | window.ScrollableMap = function (div, type, id, prefs) { 4 | 5 | let enabled = false; 6 | 7 | function enable() { 8 | if (enabled) return; 9 | enabled = true; 10 | if (DEBUG) console.log('map loaded', type); 11 | chrome.runtime.sendMessage({ 'action': 'mapLoaded' }); 12 | refreshActivationAffordance(); 13 | div.setAttribute('data-scrollmaps', 'enabled'); 14 | } 15 | 16 | function _findAncestorScrollMap(node) { 17 | if (!(node instanceof Element)) { 18 | return null; 19 | } 20 | if (node.hasAttribute('data-scrollmaps')) { 21 | return node; 22 | } 23 | return _findAncestorScrollMap(node.parentNode); 24 | } 25 | 26 | function _findDescendantScrollMap(node) { 27 | return node.querySelector('[data-scrollmaps]'); 28 | } 29 | 30 | function _findLineageScrollMap(node) { 31 | return _findDescendantScrollMap(node) 32 | || _findAncestorScrollMap(node.parentNode); 33 | } 34 | 35 | let lineage = _findLineageScrollMap(div); 36 | if (lineage != null) { 37 | if (DEBUG) { 38 | console.log('Scrollmap already added', lineage, div); 39 | } 40 | return; 41 | } 42 | 43 | if (DEBUG) { 44 | console.log('Creating scrollable map', div, id); 45 | } 46 | 47 | // Avoid adding multiple event listeners to the same map 48 | if (div.__scrollMapAttached) return; 49 | div.__scrollMapAttached = true; 50 | 51 | const self = this; 52 | 53 | let mapClicked; // whether the map has ever been clicked (to activate the map) 54 | let bodyScrolls = false; 55 | 56 | div.setAttribute('data-scrollmaps', 'false'); 57 | 58 | const style = document.createElement('style'); 59 | style.innerHTML = ` 60 | [data-scrollmaps]::after { 61 | all: initial; 62 | transition: outline 0.3s; 63 | outline: 3px solid rgba(33, 150, 243, 0); 64 | outline-offset: -3px; 65 | } 66 | [data-scrollmaps]::before { 67 | all: initial; 68 | transition: opacity 0.3s 0s, background 0.3s 0s; 69 | opacity: 0; 70 | text-shadow: 0 0 7px #fff; 71 | pointer-events: none; 72 | } 73 | [data-scrollmaps].scrollMapsActivatable:hover::after { 74 | outline: 3px solid rgba(33, 150, 243, 0.5); 75 | } 76 | [data-scrollmaps].scrollMapsActivatable::before { 77 | content: 'Click to activate ScrollMaps'; 78 | white-space: nowrap; 79 | font-family: 'Arial', sans-serif; 80 | font-size: 14px; 81 | display: inline-block; 82 | position: absolute; 83 | z-index: 9999; 84 | top: 3px; left: 50%; 85 | transform: translateX(-50%); 86 | background: linear-gradient(rgba(33, 150, 243, 0.5) 0%, rgba(33, 150, 243, 0.8) 40%); 87 | padding: 0 7px 2px 7px; 88 | border-radius: 0 0 8px 8px; 89 | text-align: center; 90 | color: #333; 91 | } 92 | [data-scrollmaps].scrollMapsActivatable:hover::before { 93 | opacity: 1; 94 | } 95 | [data-scrollmaps].scrollMapsActivatable::after { 96 | content: ''; 97 | display: block; 98 | position: absolute; 99 | top: 0px; left: 0px; right: 0px; bottom: 0px; 100 | pointer-events: none; 101 | z-index: 9999; 102 | } 103 | [data-scrollmaps].scrollMapsActivated::before, 104 | [data-scrollmaps].scrollMapsActivated:hover::before { 105 | content: 'ScrollMaps activated'; 106 | white-space: nowrap; 107 | opacity: 1; 108 | animation: fadeOutActivatedBanner 1s ease-in 3s forwards; 109 | background: rgba(33, 150, 243, 0.8); 110 | } 111 | @keyframes fadeOutActivatedBanner { 112 | to { 113 | opacity: 0; 114 | } 115 | } 116 | [data-scrollmaps].scrollMapsActivated::after, 117 | [data-scrollmaps].scrollMapsActivated:hover::after { 118 | outline: 3px solid rgba(33, 150, 243, 0.8); 119 | } 120 | `; 121 | document.head.appendChild(style); 122 | 123 | Scrollability.monitorScrollabilitySuper(div, (scrolls) => { 124 | bodyScrolls = scrolls; 125 | refreshActivationAffordance(); 126 | }); 127 | 128 | var States = { idle: 0, scrolling: 1, zooming: 2 }; 129 | var state = States.idle; 130 | 131 | var averageX = new SMLowPassFilter(2); 132 | var averageY = new SMLowPassFilter(2); 133 | 134 | var accelero = new SM2DAccelerationDetector(); 135 | 136 | self.init = function (div, type) { 137 | self.type = type; 138 | div.addEventListener('wheel', self.handleWheelEvent, true); 139 | 140 | mapClicked = false; 141 | 142 | Pref.onPreferenceChanged(null, (key, value) => { 143 | switch (key) { 144 | case 'frameRequireFocus': 145 | refreshActivationAffordance(); 146 | break; 147 | case 'enabled': 148 | if (value) enable(); 149 | break; 150 | } 151 | prefs[key] = value; 152 | }); 153 | 154 | chrome.runtime.onMessage.addListener((request, sender, sendResponse) => { 155 | if (request.action === 'browserActionClicked') { 156 | enable(); 157 | } 158 | }); 159 | 160 | if (window.SCROLLMAPS_enabled || prefs['enabled']) { 161 | enable(); 162 | } 163 | 164 | div.addEventListener('click', (event) => { 165 | if (_isMapActivatable()) { 166 | if (event) event.stopPropagation(); 167 | mapClicked = true; 168 | div.focus(); 169 | } 170 | refreshActivationAffordance(); 171 | lastTarget = null; 172 | }, true); 173 | const blockEventIfNotActivated = (event) => { 174 | if (_isMapActivatable()) { 175 | event.stopPropagation(); 176 | event.preventDefault(); 177 | } 178 | } 179 | div.addEventListener('mousedown', blockEventIfNotActivated, true); 180 | div.addEventListener('mouseup', blockEventIfNotActivated, true) 181 | div.addEventListener('mouseleave', () => { 182 | mapClicked = false; 183 | refreshActivationAffordance(); 184 | }); 185 | setTimeout(refreshActivationAffordance, 500); 186 | 187 | // Observe if the scroll map element is removed. Send a message to the background 188 | // page so it can update the browser action status. 189 | const mutationObserver = new MutationObserver((mutationList, observer) => { 190 | const hasRemovedNodes = mutationList.some(m => m.removedNodes.length > 0); 191 | if (hasRemovedNodes && !document.contains(div)) { 192 | chrome.runtime.sendMessage({ action: 'mapUnloaded' }); 193 | } 194 | }); 195 | mutationObserver.observe(document.documentElement, { childList: true, subtree: true }); 196 | 197 | window.addEventListener('unload', () => { 198 | // For the case where ScrollMap is loaded in an iframe, and that iframe is removed. 199 | chrome.runtime.sendMessage({ action: 'mapUnloaded' }); 200 | }); 201 | 202 | const onRealPointerMove = (e) => { 203 | if (e.detail !== 88) { 204 | if (lastTarget && dragger.mouseDownPoint) { 205 | dragger.simulateMouseUp(lastTarget); 206 | } 207 | } 208 | }; 209 | 210 | // Attach to both event listeners to make sure our mouse-up code is run before any 211 | // custom event handlers from the maps. 212 | window.addEventListener('mousemove', onRealPointerMove, true); 213 | window.addEventListener('pointermove', onRealPointerMove, true); 214 | 215 | window.addEventListener('mousemove', function (e) { 216 | if (e.detail !== 88) { 217 | const style = e.target.parentNode.style; 218 | if (style && style.cursor !== 'pointer') { 219 | dragger.lastAutoCursorPos = [e.clientX, e.clientY]; 220 | } 221 | } 222 | }, false); 223 | } 224 | 225 | // A map is activatable when 226 | // 1. relevant settings and scrollability requirements are met, and 227 | // 2. it is not currently activated. 228 | function _isMapActivatable() { 229 | return _isMapActivatableOrActivated() && 230 | !mapClicked; 231 | } 232 | 233 | function _isMapActivatableOrActivated() { 234 | return self.type !== ScrollableMap.TYPE_GOOGLE_MAPS_WEB && // Web maps are never activatable 235 | bodyScrolls && 236 | prefs['frameRequireFocus'] && 237 | enabled; 238 | } 239 | 240 | function refreshActivationAffordance() { 241 | if (_isMapActivatableOrActivated()) { 242 | div.classList.add('scrollMapsActivatable'); 243 | div.classList.toggle('scrollMapsActivated', mapClicked); 244 | } else { 245 | div.classList.remove('scrollMapsActivatable'); 246 | div.classList.remove('scrollMapsActivated'); 247 | } 248 | } 249 | 250 | // See the documentation in DRAG_SIMULATOR_DEFAULT_OPTS 251 | let maxDistanceUntilUp = 600; 252 | if (type === ScrollableMap.TYPE_GOOGLE_MAPS_LEGACY 253 | || type === ScrollableMap.TYPE_GOOGLE_MAPS_API 254 | || type === ScrollableMap.TYPE_GOOGLE_MAPS_IFRAME 255 | || type === ScrollableMap.TYPE_GOOGLE_MAPS_WEB) { 256 | maxDistanceUntilUp = div.offsetWidth && (div.offsetWidth * 0.5) || 600; 257 | } else { 258 | maxDistanceUntilUp = Infinity; 259 | } 260 | const dragger = new DragSimulator(type, { 261 | maxDistanceUntilUp 262 | }); 263 | 264 | self.move = function (point, dx, dy, target) { 265 | dragger.simulateDrag(target, point, dx, dy); 266 | }; 267 | 268 | const PINCH_ZOOM_SCALE = { 269 | [ScrollableMap.TYPE_GOOGLE_MAPS_LEGACY]: 8, 270 | [ScrollableMap.TYPE_GOOGLE_MAPS_IFRAME]: 8, 271 | [ScrollableMap.TYPE_GOOGLE_MAPS_API]: 8, 272 | [ScrollableMap.TYPE_GOOGLE_MAPS_WEB]: 1, 273 | [ScrollableMap.TYPE_ARCGIS]: 1.1, 274 | [ScrollableMap.TYPE_MAPBOX]: 3, 275 | [ScrollableMap.TYPE_LEAFLET]: 3, 276 | [ScrollableMap.TYPE_OPEN_STREET_MAP]: 0.8, 277 | [ScrollableMap.TYPE_APPLE_MAPKIT]: 1, 278 | [ScrollableMap.TYPE_MAPLIBRE]: 4, 279 | [ScrollableMap.TYPE_MAPYCZ]: 4, 280 | }; 281 | 282 | // How much deltaY should correspond to a zoom level. 0 if scrolling is smooth. 283 | const ZOOM_STEP = { 284 | [ScrollableMap.TYPE_GOOGLE_MAPS_LEGACY]: 50, 285 | [ScrollableMap.TYPE_GOOGLE_MAPS_IFRAME]: 50, 286 | [ScrollableMap.TYPE_GOOGLE_MAPS_API]: 50, 287 | [ScrollableMap.TYPE_GOOGLE_MAPS_WEB]: 50, 288 | [ScrollableMap.TYPE_ARCGIS]: 50, 289 | [ScrollableMap.TYPE_MAPBOX]: 50, 290 | [ScrollableMap.TYPE_LEAFLET]: 50, 291 | [ScrollableMap.TYPE_OPEN_STREET_MAP]: 50, 292 | [ScrollableMap.TYPE_APPLE_MAPKIT]: 0, 293 | [ScrollableMap.TYPE_MAPLIBRE]: 0, 294 | [ScrollableMap.TYPE_MAPYCZ]: 50, 295 | }; 296 | 297 | const TIME_THROTTLE = { 298 | [ScrollableMap.TYPE_GOOGLE_MAPS_LEGACY]: 400, 299 | [ScrollableMap.TYPE_GOOGLE_MAPS_IFRAME]: 400, 300 | [ScrollableMap.TYPE_GOOGLE_MAPS_API]: 400, 301 | [ScrollableMap.TYPE_GOOGLE_MAPS_WEB]: 0, 302 | [ScrollableMap.TYPE_ARCGIS]: 0, 303 | [ScrollableMap.TYPE_MAPBOX]: 0, 304 | [ScrollableMap.TYPE_LEAFLET]: 0, 305 | [ScrollableMap.TYPE_OPEN_STREET_MAP]: 0, 306 | [ScrollableMap.TYPE_APPLE_MAPKIT]: 0, 307 | [ScrollableMap.TYPE_MAPLIBRE]: 0, 308 | [ScrollableMap.TYPE_MAPYCZ]: 400, 309 | }; 310 | 311 | const zoomDeltaTracker = new ZoomDeltaTracker(ZOOM_STEP[type], TIME_THROTTLE[type]); 312 | 313 | self.zoomInOrOut = function (mousePos, target, originalEvent, isZoomIn) { 314 | // New Google Maps zooms much better with respect to unmodified mouse wheel events. Let's 315 | // keep that behavior for Cmd-scrolling. 316 | if (originalEvent instanceof WheelEvent) { 317 | // Scale the pinch gesture 3x for non-web maps, because pinch gesture normally 318 | // have much less "delta" than scroll 319 | let delta = originalEvent.deltaY; 320 | if (originalEvent.ctrlKey) { 321 | delta *= prefs['zoomSpeed'] / 100; 322 | delta *= PINCH_ZOOM_SCALE[type]; 323 | if (type === ScrollableMap.TYPE_GOOGLE_MAPS_WEB && isWebGlCanvas(target)) { 324 | // Special case: Google maps web scrolling is smooth when in webGL mode, but 325 | // we only just got the event target to know about that. 326 | } else { 327 | // For 2d canvas (try with ?force=canvas in the URL), the zooming doesn't 328 | // behave naturally. It zooms a specific increment on each wheel event 329 | // and doesn't look at deltaY. Throttle the number of events to keep the 330 | // zooming at a reasonable rate. 331 | const trackerDelta = zoomDeltaTracker.zoomDelta(delta); 332 | if (trackerDelta === false) { 333 | return; 334 | } else { 335 | delta = trackerDelta; 336 | } 337 | } 338 | } 339 | 340 | const events = createBackdoorWheelEvents(originalEvent, isZoomIn, delta); 341 | for (const eventInit of events) { 342 | target.dispatchEvent(new WheelEvent('wheel', eventInit)); 343 | target.dispatchEvent(new WheelEvent('mousewheel', { 344 | ...eventInit, 345 | deltaY: eventInit.deltaY, 346 | detail: eventInit.deltaY, 347 | })); 348 | if (window.MouseScrollEvent) { 349 | // Very old and deprecated mouse scroll event used by Firefox. 350 | // OpenStreetMap still uses this event when it detects that the browser is Firefox. 351 | // https://developer.mozilla.org/en-US/docs/Web/API/Element/DOMMouseScroll_event 352 | const domMouseScrollEvent = new MouseEvent('DOMMouseScroll', { 353 | ...eventInit, 354 | detail: eventInit.deltaY / 16, 355 | shiftKey: type === ScrollableMap.TYPE_ARCGIS, 356 | }); 357 | target.dispatchEvent(domMouseScrollEvent); 358 | if (type === ScrollableMap.TYPE_ARCGIS) { 359 | target.dispatchEvent(new MouseEvent('MozMousePixelScroll', { 360 | ...eventInit, 361 | detail: eventInit.deltaY / 16, 362 | shiftKey: true, 363 | })); 364 | } 365 | } 366 | } 367 | return; 368 | } else { 369 | console.warn('ScrollMaps unexpected event', originalEvent); 370 | } 371 | }; 372 | 373 | self.zoomIn = function (mousePos, target, originalEvent) { 374 | return self.zoomInOrOut(mousePos, target, originalEvent, /* isZoomIn= */ true); 375 | }; 376 | 377 | self.zoomOut = function (mousePos, target, originalEvent) { 378 | return self.zoomInOrOut(mousePos, target, originalEvent, /* isZoomIn= */ false); 379 | }; 380 | 381 | function createBackdoorWheelEvents(originalEvent, zoomIn, delta) { 382 | if (originalEvent instanceof WheelEvent) { 383 | const init = {}; 384 | for (const i in originalEvent) { 385 | init[i] = originalEvent[i]; 386 | } 387 | init.detail = 10888; 388 | 389 | if (zoomIn && delta > 0) { 390 | delta *= -1; 391 | } else if (!zoomIn && delta < 0) { 392 | delta *= -1; 393 | } 394 | init.deltaY = delta; 395 | 396 | if (type === ScrollableMap.TYPE_MAPBOX || type === ScrollableMap.TYPE_MAPLIBRE) { 397 | // Mapbox has this trackpad detection logic that we might confuse when we increase our zoom speed. 398 | // https://github.com/mapbox/mapbox-gl-js/blob/c708474eb65d9c6a117fe232b677db19525f70b4/src/ui/handler/scroll_zoom.js#L17-L22 399 | // Split the wheel event into many with small delta to make sure it's treated as trackpad 400 | const numEvents = Math.ceil(Math.abs(delta / 4)); 401 | return Array(numEvents).fill({ ...init, deltaY: init.deltaY / numEvents }); 402 | } else { 403 | return [init]; 404 | } 405 | } else { 406 | console.log('Trying to create backdoor event out of non-wheel event', originalEvent); 407 | } 408 | } 409 | 410 | function isWebGlCanvas(target) { 411 | if (!(target instanceof HTMLCanvasElement)) return false; 412 | return !!target.getContext('webgl'); 413 | } 414 | 415 | var lastTarget; 416 | self.handleWheelEvent = function (e) { 417 | if (!enabled && !window.safari) return; 418 | if (_isMapActivatable()) { 419 | e.stopPropagation(); return; 420 | } 421 | 422 | if (e.detail == 10888) { 423 | return; // backdoor for zooming 424 | } 425 | 426 | var target = e.target || e.srcElement; 427 | var isAccelerating = accelero.isAccelerating(e.deltaX, e.deltaY, e.timeStamp); 428 | 429 | if (Scrollability.hasScrollableParent(target, div)) { 430 | // something is scrollable, let's allow it to scroll 431 | return; 432 | } 433 | 434 | if (lastTarget && div.contains(lastTarget)) { 435 | target = lastTarget; 436 | } else { 437 | lastTarget = target; 438 | } 439 | 440 | var destinationState = (e.metaKey || e.ctrlKey || e.altKey) ? States.zooming : States.scrolling; 441 | if (isAccelerating || state == destinationState) { 442 | state = destinationState; 443 | var mousePos = [e.clientX, e.clientY]; 444 | 445 | switch (state) { 446 | case States.zooming: 447 | // In Chrome, ctrl + wheel => pinch gesture. Do not invert zoom for the pinch 448 | // gesture. 449 | var factor = (prefs['invertZoom'] && !(window.chrome && e.ctrlKey)) ? -1 : 1; 450 | if (window.safari && e.webkitDirectionInvertedFromDevice) { 451 | factor *= -1; 452 | } 453 | if (e.deltaY * factor < 0) { 454 | self.zoomIn(mousePos, target, e); 455 | } else if (e.deltaY * factor > 0) { 456 | self.zoomOut(mousePos, target, e); 457 | } 458 | break; 459 | case States.scrolling: 460 | setTimer('flushAverage', function () { averageX.flush(); averageY.flush(); }, 200); 461 | averageX.push(e.deltaX); averageY.push(e.deltaY); 462 | 463 | const speedFactor = (prefs['scrollSpeed'] / 100) * (prefs['invertScroll'] ? 1 : -1); 464 | let dx = averageX.getAverage() * speedFactor; 465 | let dy = averageY.getAverage() * speedFactor; 466 | dx = dx * Math.pow(Math.abs(dx), 0.20) * 0.80; 467 | dy = dy * Math.pow(Math.abs(dy), 0.20) * 0.80; 468 | 469 | if (dx !== 0 || dy !== 0) { 470 | self.move(mousePos, dx, dy, target); 471 | } 472 | break; 473 | } 474 | } else { 475 | state = States.idle; 476 | } 477 | e.stopPropagation(); 478 | e.preventDefault(); 479 | return false; 480 | }; 481 | 482 | self.init(div, type); 483 | 484 | }; 485 | 486 | function setTimer(timerID, newFunction, newDelay) { 487 | window._timers = window._timers || {}; 488 | clearTimeout(window._timers[timerID]); 489 | window._timers[timerID] = setTimeout(newFunction, newDelay); 490 | } 491 | 492 | ScrollableMap.TYPE_GOOGLE_MAPS_LEGACY = 0; 493 | ScrollableMap.TYPE_GOOGLE_MAPS_IFRAME = 1; 494 | ScrollableMap.TYPE_GOOGLE_MAPS_API = 2; 495 | ScrollableMap.TYPE_GOOGLE_MAPS_WEB = 3; 496 | ScrollableMap.TYPE_ARCGIS = 4; 497 | ScrollableMap.TYPE_MAPBOX = 5; 498 | ScrollableMap.TYPE_OPEN_STREET_MAP = 6; 499 | ScrollableMap.TYPE_APPLE_MAPKIT = 7; 500 | ScrollableMap.TYPE_MAPLIBRE = 8; 501 | ScrollableMap.TYPE_LEAFLET = 9; 502 | ScrollableMap.TYPE_MAPYCZ = 10; 503 | 504 | /** 505 | * Tracker for mouse wheel events, to throttle the zoom level. 506 | * 507 | * Some maps use the number of events to determine how much to zoom and ignore the delta amount; 508 | * for the "smooth" pinch gesture that generates a large number of events with small delta 509 | * values this results in what I call "crazy zooming". This tracker negates that effect by 510 | * keeping track of the accumulated zoom delta, and trigger one real zoom event only if a 511 | * certain threshold is reached. 512 | */ 513 | class ZoomDeltaTracker { 514 | constructor(deltaPerZoomLevel, timeThrottle) { 515 | this.accumulatedZoomDelta = 0; 516 | this.lastZoomTime = 0; 517 | this.deltaPerZoomLevel = deltaPerZoomLevel; 518 | this.timeThrottle = timeThrottle; 519 | } 520 | 521 | /** 522 | * Add `delta` to the zoom tracker. 523 | * 524 | * @returns `false` if the tracker should not be zooming, or a number indicating the 525 | * accumulated zoom amount. 526 | */ 527 | zoomDelta(delta) { 528 | if (this.deltaPerZoomLevel === 0) { 529 | return delta; 530 | } 531 | if (Date.now() - this.lastZoomTime > 1000) this.accumulatedZoomDelta = 0; 532 | this.accumulatedZoomDelta += delta; 533 | this.lastZoomTime = Date.now(); 534 | if (delta < 0) { 535 | // Zoom in 536 | if (this.accumulatedZoomDelta > -this.deltaPerZoomLevel) return false; 537 | this.accumulatedZoomDelta += this.deltaPerZoomLevel; 538 | } else if (delta > 0) { 539 | // Zoom out 540 | if (this.accumulatedZoomDelta < this.deltaPerZoomLevel) return false; 541 | this.accumulatedZoomDelta -= this.deltaPerZoomLevel; 542 | } 543 | return this.deltaPerZoomLevel; 544 | } 545 | } 546 | 547 | const SM_LOW_PASS_FILTER_SMOOTHING = 0.5; 548 | 549 | class SMLowPassFilter { 550 | constructor() { 551 | this.data = 0; 552 | this.lastDataTime = 0; 553 | } 554 | 555 | push(data, time) { 556 | this.data = this.data * SM_LOW_PASS_FILTER_SMOOTHING + data * (1 - SM_LOW_PASS_FILTER_SMOOTHING); 557 | this.lastDataTime = time || Date.now(); 558 | } 559 | 560 | getAverage(time) { 561 | time = time || Date.now(); 562 | if (this.lastDataTime === 0) { 563 | return this.data; 564 | } 565 | return this.data * Math.pow(SM_LOW_PASS_FILTER_SMOOTHING, (time - this.lastDataTime) / 20); 566 | } 567 | 568 | flush() { 569 | this.data = 0; 570 | } 571 | } 572 | 573 | class SMAccelerationDetector { 574 | constructor() { 575 | this.max = 0; 576 | this.maxTime = 0; 577 | this.lastDelta = 0; 578 | this.lastTime = Date.now(); 579 | } 580 | 581 | isAccelerating(delta, time) { 582 | delta = delta / (time - this.lastTime); 583 | setTimer('stateChangeTimer', this.newScrollAction.bind(this), 200); 584 | 585 | var output = false; 586 | 587 | if (Math.abs(delta) > Math.abs(this.max)) { 588 | this.max = delta; 589 | this.maxTime = time; 590 | output = true; 591 | } 592 | var t = time - this.maxTime; 593 | var prediction = this.max * Math.exp(-0.0038 * t); 594 | 595 | var difference = (Math.abs(delta) - Math.abs(prediction)); 596 | 597 | if (difference / Math.abs(prediction) > 1.2 && difference > 0.5) { 598 | this.newScrollAction(); 599 | output = true; 600 | } 601 | return output; 602 | } 603 | 604 | newScrollAction() { 605 | this.max = 0; 606 | this.maxTime = 0; 607 | this.lastDelta = 0; 608 | } 609 | } 610 | 611 | class SM2DAccelerationDetector { 612 | constructor() { 613 | this.yAccelerationDetector = new SMAccelerationDetector(); 614 | this.xAccelerationDetector = new SMAccelerationDetector(); 615 | } 616 | 617 | isAccelerating(deltaX, deltaY, time) { 618 | var x = this.xAccelerationDetector.isAccelerating(deltaX, time); 619 | var y = this.yAccelerationDetector.isAccelerating(deltaY, time); 620 | return x || y; 621 | } 622 | } 623 | 624 | const DRAG_SIMULATOR_DEFAULT_OPTS = { 625 | // The minimum distance to simulate a drag, to avoid the event being interpreted as 626 | // a click. If the scroll gesture's distance is smaller than this, it will be scaled 627 | // up to reach this distance. 628 | 'minDragDistance': 3, 629 | // The maximum distance that can be scrolled (along either X or Y axis) before a 630 | // mouse up is force triggered. This is useful for street view where the panning 631 | // is non-linear, so that the panning response will reset one in a while. 632 | // If this value is too large, the stree view will stop panning until you want for 633 | // the mouse-up timeout. If this value is too small, the event may be treated as a 634 | // mouse move rather than a drag. 635 | 'maxDistanceUntilUp': 600, 636 | // The delay in milliseconds before a mouse up is simulated, after the last call to 637 | // simulateDrag. This is non-zero for newer implementations tend to have inertial-drag 638 | // which tracks the mouse events over time, and therefore firing mousedown + mousemove 639 | // + mouseup events in the same loop synchronously will not work. 640 | 'mouseUpDelay': 100, 641 | }; 642 | 643 | class DragSimulator { 644 | constructor(mapType, opts) { 645 | this.mapType = mapType; 646 | this.opts = { ...DRAG_SIMULATOR_DEFAULT_OPTS, ...opts }; 647 | } 648 | 649 | // Dispatch mouse and pointer events 650 | _dispatchPointerEvent(target, type, opts) { 651 | const mouseEvent = new MouseEvent('mouse' + type, opts); 652 | const pointerEvent = new PointerEvent('pointer' + type, { pointerId: 10088, isPrimary: true, ...opts }); 653 | target.dispatchEvent(mouseEvent); 654 | target.dispatchEvent(pointerEvent); 655 | } 656 | 657 | simulateMouseDown(target, point) { 658 | this.mouseDownPoint = [point[0], point[1]]; // Deep copy 659 | this.simulatedMousePoint = point; 660 | const eventOpts = { 661 | 'bubbles': true, 662 | 'cancelable': true, 663 | 'detail': 1, 664 | 'clientX': point[0], 665 | 'clientY': point[1], 666 | 'button': 0, 667 | 'buttons': 1, 668 | 'pressure': 0.5, 669 | }; 670 | this._dispatchPointerEvent(target, 'down', eventOpts); 671 | } 672 | 673 | simulateMouseUp(target) { 674 | if (!this.mouseDownPoint) return; 675 | 676 | // If the minimum drag distance is not reached, dispatch an extra move event 677 | let dx = this.simulatedMousePoint[0] - this.mouseDownPoint[0]; 678 | let dy = this.simulatedMousePoint[1] - this.mouseDownPoint[1]; 679 | const minDragDistance = this.opts.minDragDistance; 680 | if (Math.abs(dx) < minDragDistance && Math.abs(dy) < minDragDistance) { 681 | // scale to make sure at least one of them is > minDragDistance 682 | // this ensures it's treated as a drag, not a click 683 | const scale = (minDragDistance * 1.05) / Math.max(Math.abs(dx), Math.abs(dy), 1); 684 | this.simulateMouseMove(target, dx * scale, dy * scale); 685 | } 686 | 687 | this._dispatchPointerEvent(target, 'up', { 688 | 'bubbles': true, 689 | 'cancelable': true, 690 | 'detail': 1, 691 | 'clientX': this.simulatedMousePoint[0], 692 | 'clientY': this.simulatedMousePoint[1], 693 | 'button': 0, 694 | 'buttons': 0, 695 | 'pressure': 0, 696 | }); 697 | 698 | // Trigger a move event so that map updates the cursor based on the current cursor position. 699 | this._dispatchPointerEvent(target, 'move', { 700 | 'bubbles': true, 701 | 'cancelable': false, 702 | 'detail': 88, 703 | 'clientX': this.mouseDownPoint[0], 704 | 'clientY': this.mouseDownPoint[1], 705 | 'button': 0, 706 | 'buttons': 0, 707 | 'pressure': 0, 708 | }) 709 | 710 | this.lastAutoCursorPos = [this.simulatedMousePoint[0], this.simulatedMousePoint[1]]; 711 | this.mouseDownPoint = null; 712 | } 713 | 714 | simulateMouseMove(target, dx, dy) { 715 | this.simulatedMousePoint[0] += dx; 716 | this.simulatedMousePoint[1] += dy; 717 | const eventOpts = { 718 | 'bubbles': true, 719 | 'cancelable': false, 720 | 'detail': 88, 721 | 'clientX': this.simulatedMousePoint[0], 722 | 'clientY': this.simulatedMousePoint[1], 723 | 'button': 0, 724 | 'buttons': 1, // Left mouse button should be down when simulating drag-move 725 | 'pressure': 0.5, 726 | }; 727 | this._dispatchPointerEvent(target, 'move', eventOpts); 728 | } 729 | 730 | simulateDrag(target, point, dx, dy) { 731 | if (!this.mouseDownPoint) { 732 | // In Google maps, if a hover card is shown, it might be a hint that dragging does something other than 733 | // panning the map. Unfortunately, I couldn't find a more useful indicator to tell that, so we may be 734 | // playing a little cat-and-mouse game here. 735 | const hasDragHint = this.mapType === ScrollableMap.TYPE_GOOGLE_MAPS_WEB 736 | && Array.from(document.querySelectorAll('[jsaction*="hovercard"]')) 737 | .some(e => e.style.display !== "none") 738 | if (hasDragHint && this.lastAutoCursorPos) { 739 | // If the cursor style is pointer, we might be hovering on a route. Dragging 740 | // will alter the route, which we don't want, so use the last mouse down point 741 | // instead. 742 | this.simulateMouseDown(target, this.lastAutoCursorPos); 743 | } else { 744 | this.simulateMouseDown(target, point); 745 | } 746 | } 747 | 748 | this.simulateMouseMove(target, dx, dy); 749 | 750 | // Street view panning has set an exponential decaying curve, in order for the scroll 751 | // to continue, pretend a mouse up every so often. 752 | // There is a visible jump when this happens if you observe carefully, but the results 753 | // are good enough for general use. 754 | const maxDistanceUntilUp = this.opts.maxDistanceUntilUp; 755 | if (Math.abs(this.simulatedMousePoint[0] - this.mouseDownPoint[0]) > maxDistanceUntilUp || 756 | Math.abs(this.simulatedMousePoint[1] - this.mouseDownPoint[1]) > maxDistanceUntilUp) { 757 | this.simulateMouseUp(target); 758 | } 759 | 760 | if (this.opts.mouseUpDelay > 0) { 761 | window.clearTimeout(this.timer); 762 | this.timer = window.setTimeout( 763 | this.simulateMouseUp.bind(this, target), 764 | this.opts.mouseUpDelay); 765 | } 766 | } 767 | } 768 | 769 | } 770 | --------------------------------------------------------------------------------