-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
How to execute a user script before a page is saved
Gildas edited this page Sep 27, 2019
·
38 revisions
-
Enable the hidden option
userScriptEnabled
by exporting the settings from the options page, editing the JSON file, replacinguserScriptEnabled: false
withuserScriptEnabled: true
, and importing the modified file in SingleFile. -
Dispatch the custom event
single-file-user-script-init
in the user script.
dispatchEvent(new CustomEvent("single-file-user-script-init"));
- Listen to the custom event
single-file-on-capture-request
in the user script. The listener function is called just before the page is saved.
addEventListener("single-file-on-capture-request", () => {
console.log("The page will be saved by SingleFile");
});
If the listener function has to be async
, call event.preventDefault()
and dispatch the custom event single-file-on-capture-response
once the asynchronous tasks are terminated.
addEventListener("single-file-on-capture-request", async event => {
event.preventDefault();
try {
await ...
} finally {
dispatchEvent(new CustomEvent("single-file-on-capture-response"));
}
});
- The complete example below shows how to remove images from the page just before saving it.
// ==UserScript==
// @name Remove images
// @namespace http://tampermonkey.net/
// @version 0.1
// @description [SingleFile] Remove all the images
// @author Gildas Lormeau
// @match *://*/*
// @grant none
// ==/UserScript==
(() => {
const EMPTY_IMAGE = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==";
dispatchEvent(new CustomEvent("single-file-user-script-init"));
addEventListener("single-file-on-capture-request", event => {
Array.from(document.images).forEach(image => {
image.setAttribute("src", EMPTY_IMAGE);
image.removeAttribute("data-src");
image.removeAttribute("data-srcset");
image.removeAttribute("srcset");
image.removeAttribute("data-single-file-lazy-loaded-src");
});
});
})();