Rewrite Microsoft Safe Links

Rewrites links starting with "https://*.safelinks.protection.outlook.com" to link to the website immediately. This feature comes from "Microsoft Defender for Office 365". Also disables any scanning for potential phishing sites, see also https://learn.microsoft.com/en-us/microsoft-365/security/office-365-security/safe-links-about?view=o365-worldwide

  1. // ==UserScript==
  2. // @name Rewrite Microsoft Safe Links
  3. // @include https://outlook.office.com/*
  4. // @author Pieter Bos
  5. // @description Rewrites links starting with "https://*.safelinks.protection.outlook.com" to link to the website immediately. This feature comes from "Microsoft Defender for Office 365". Also disables any scanning for potential phishing sites, see also https://learn.microsoft.com/en-us/microsoft-365/security/office-365-security/safe-links-about?view=o365-worldwide
  6. // @license CC-BY-2.0
  7. // @version 2
  8. // @grant none
  9. // @run-at document-start
  10. // @namespace https://greasyfork.org/users/1167928
  11. // ==/UserScript==
  12.  
  13. const URL_PATTERN = new RegExp('^https://[a-zA-Z0-9]+\\.safelinks\\.protection\\.outlook\\.com/');
  14.  
  15. const config = { childList: true, subtree: true, characterData: false, attributes: true };
  16.  
  17. const onMutate = (mutationList, observer) => {
  18. for(const mutation of mutationList) {
  19. for(const addedNode of mutation.addedNodes) {
  20. for(const anchor of addedNode.querySelectorAll('a')) {
  21. try {
  22. if(!URL_PATTERN.test(anchor.href)) continue;
  23. const params = new URLSearchParams(new URL(anchor.href).search);
  24. if(!params.has('url')) continue;
  25.  
  26.  
  27. if(anchor.textContent === anchor.href) anchor.textContent = params.get('url');
  28. anchor.href = params.get('url');
  29.  
  30. // Delete onclick event handler that goes to safelinks anyway by cloning the element
  31. const freshElem = anchor.cloneNode(true);
  32. anchor.replaceWith(freshElem);
  33. } catch {}
  34. }
  35. }
  36. }
  37. };
  38.  
  39. const observer = new MutationObserver(onMutate);
  40. observer.observe(document, config);