Tampermonkey userscripts

After many years of wanting to use userscripts, I finally have a use case! Time to learn about how to create those. Docs for the API and headers are here.

Helpful idioms (from here):

Userscript idioms and code snippets

  • Query and remove a page element:
document.querySelector("#element_id").remove();
  • Store an object:
GM_setValue("MY_OBJECT_KEY", JSON.stringify(myObject));
  • Retrieve an object:
var myObject = JSON.parse(GM_getValue("MY_OBJECT_KEY", "{}"));
  • Replace the current URL and redirect the page:
var link = document.URL.replace("domain.fr", "domain.com");
window.location.href=link;
  • Add a button to execute some function on the page:
var btn = document.createElement("button");
btn.innerHTML = "My button";
btn.onclick = () => {
    alert("My button clicked !");
    return false;
};
document.querySelector("btn_predecessor_selector").after(btn);
  • Append a style to the page:
var css = "h1 { background: red; }"
var style = document.createElement("style");
style.type = "text/css";
style.appendChild(document.createTextNode(css));
document.head.appendChild(style);
  • Fetching and parsing an external page:
fetch("http://example.com/path-name")
.then(response => response.text())
.then(text => {
    var parser = new DOMParser();
    var htmlDocument = parser.parseFromString(text, "text/html");
    var content = htmlDocument.documentElement.querySelector("element_selector");
    alert("My fetched element content: " + content.textContent);
});

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Create your website with WordPress.com
Get started
%d bloggers like this: