Skip to content

Commit

Permalink
fix: redirect on click
Browse files Browse the repository at this point in the history
Instead of changing links, use a JS script that hijacks all click
events and redirects to rickroll.

This works way better (no more trouble with JS navigation), and
the rickroll link doesn't show on hover anymore.
  • Loading branch information
derlin committed Apr 5, 2022
1 parent f88d8a0 commit aefe986
Showing 1 changed file with 28 additions and 10 deletions.
38 changes: 28 additions & 10 deletions rickroll/rickroller.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,33 +4,32 @@
import re


class RickRoller:
__RICK_ROLL_URL__ = "https://www.youtube.com/watch?v=dQw4w9WgXcQ"

__RICK_ROLL_URL__ = "https://www.youtube.com/watch?v=dQw4w9WgXcQ"

class RickRoller:
@classmethod
def rickroll(self, url: str) -> str:
soup = self.__get_soup(url)

for a in soup.find("body").find_all("a"):
a.attrs["href"] = self.__RICK_ROLL_URL__

args = [soup, url]
self.__absolutize("link", "href", *args)
self.__absolutize("script", "src", *args)
self.__absolutize("img", "src", *args)

self.__fix_srcset(*args)

self.__insert_js(*args)

return str(soup)

@staticmethod
def __absolutize(tagname, attr, soup, url):
def __absolutize(tagname, attr, soup, url, *args):
for elt in soup.find_all(tagname, **{attr: True}):
elt.attrs[attr] = urljoin(url, elt.attrs[attr])

@staticmethod
def __fix_srcset(soup, url):
def __fix_srcset(soup, url, *args):
# for responsive images
# e.g. "/static/563761cc22ded851baff4921ecc27649/e4a55/python-url-decode.jpg 256w, /static/563761cc22ded851baff4921ecc27649/36dd4/python-url-decode.jpg 512w, /static/563761cc22ded851baff4921ecc27649/72e01/python-url-decode.jpg 1024w, /static/563761cc22ded851baff4921ecc27649/ac99c/python-url-decode.jpg 1536w, /static/563761cc22ded851baff4921ecc27649/0f98f/python-url-decode.jpg 1920w"
for elt in soup.find_all("img", srcset=True):
Expand All @@ -42,9 +41,28 @@ def __fix_srcset(soup, url):
transformed.append(" ".join([urljoin(url, items[0])] + items[1:]))

elt.attrs["srcset"] = ",".join(transformed)
print(srcset)
print(elt.attrs["srcset"])
print("----")

@staticmethod
def __insert_js(soup, *args):
js = (
"""
document.addEventListener("DOMContentLoaded", function(event) {
document.addEventListener("click", e => {
e.stopPropagation();
e.preventDefault();
window.location = "%s"
}, true);
});
"""
% __RICK_ROLL_URL__
)

tag = soup.new_tag("script")
tag.attrs["type"] = "text/javascript"
tag.string = js

print(js)
soup.body.insert(len(soup.body.contents), tag)

@staticmethod
def __get_soup(url: str) -> BeautifulSoup:
Expand Down

0 comments on commit aefe986

Please sign in to comment.