Using Greasemonkey/Tampermonkey to replace a div object for an anchor object

Viewed 212

Some websites, such as Canon (https://www.usa.canon.com/internet/portal/us/home/about/newsroom/press-releases) have their hyperlinks shortened and embedded in a div object, preventing you from right-clicking and 'opening new tab'. I realised I can stop it by changing the div element to an anchor object.

Specifically, if I replace:

<div style ="cursor:pointer;" on click="window.location.href='/internet

with

<a href = 'https://www.usa.canon.com/internet

The html corrects itself and I can now open the link properly. Through some research, I came across Tampermonkey and I've spent the best part of 4 hours trying to write the 1-2 lines of code I would need to get it do it automatically for all instances on a webpage. Could anyone point to me to a quick resource for figuring this out?

Thank you!

1 Answers

Here is a a basic example based on the mentioned page that you can work on:

// ==UserScript==
// @name            Div to Anchor
// @match           https://www.usa.canon.com/internet/portal/us/home/about/newsroom/press-releases
// ==/UserScript==

// --- template
const temp = document.createElement('a');
temp.target = '_blank';                    // open in a new tab

document.querySelectorAll('div[onclick^="window.location.href="]').forEach(item => {
  const a = temp.cloneNode();
  a.href = item.getAttribute('onclick').slice(22, -2);
  a.textContent = item.textContent;
  item.replaceWith(a);
});
Related