Last active
July 18, 2025 11:23
-
-
Save Aran-Fey/ecb80a7d3b3a955c9841bd6bea60d515 to your computer and use it in GitHub Desktop.
Ever visited the python 2 documentation on accident? Ever got linked to the python 3.2 docs by google? Install this userscript to be automatically redirected to the version 3 docs whenever you visit docs.python.org.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // ==UserScript== | |
| // @name always python 3 docs | |
| // @description Automatically redirects from python 2 or python 3.x documentation to the latest python 3 documentation | |
| // @version 1.3.4 | |
| // @author Paul Pinterits | |
| // @include /https?://docs\.python\.org/[\d.]+/.*/ | |
| // @grant none | |
| // @run-at document-start | |
| // @updateURL https://gist.github.com/Aran-Fey/ecb80a7d3b3a955c9841bd6bea60d515/raw/always_python_3_docs.user.js | |
| // @downloadURL https://gist.github.com/Aran-Fey/ecb80a7d3b3a955c9841bd6bea60d515/raw/always_python_3_docs.user.js | |
| // ==/UserScript== | |
| (function(){ | |
| console.log(window.location.href); | |
| function regex_escape(text){ | |
| return text.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); | |
| } | |
| function replace_version(url, version){ | |
| const regex = new RegExp('(^https?://docs\.python\.org)/(?!'+regex_escape(version)+'/)([\\d.]+)(/.*)'); | |
| const repl = '$1/'+version+'$3'; | |
| return url.replace(regex, repl); | |
| } | |
| function show_version_switcher_if_404(){ | |
| // If this page has no python3 version, display a link to the python 2 version | |
| if (document.querySelector('.version_switcher_placeholder') !== null){ | |
| return; | |
| } | |
| const link = document.createElement('a'); | |
| link.href = replace_version(window.location.href, '2.7'); | |
| link.textContent = 'visit the python 2 version of this page'; | |
| const center = document.createElement('center'); | |
| center.style.paddingTop = '2em'; | |
| center.appendChild(link); | |
| document.body.appendChild(center); | |
| } | |
| // if the user came here from the docs, don't redirect | |
| const prev_url = document.referrer; | |
| if (prev_url.match('^https?://docs\.python\.org')){ | |
| show_version_switcher_if_404(); | |
| return; | |
| } | |
| const TARGET_VERSION = '3'; | |
| const target_url = replace_version(window.location.href, TARGET_VERSION); | |
| // if the url didn't change, do nothing | |
| if (target_url == window.location.href){ | |
| show_version_switcher_if_404(); | |
| return; | |
| } | |
| document.location.replace(target_url); | |
| })(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment