Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add event Listener to google sheets link in chrome extension's content script?

I'm developing a chrome extension to open links from different columns to their assigned tab. Using Google apps script API to create a context of the sheet inside the chrome extension. But Google apps script API is a long path and I can't avoid opening and closing of tabs on clicking link form sheet.

Now I want to add an event listener for click on sheet link/tooltip link. I am Already using a content script to inject a panel in the sheet.

Here is code from (content script). related to the link.

(function() {
  let sheetLinks = document.querySelectorAll('.waffle-hyperlink-tooltip-link');
  for (let i = 0; i < link.length; i++) {
    sheetLinks[i].addEventListener("click", sendHref);
  }

  function sendHref(e) {
    e.preventDefault()
    console.log('link was clicked')
  }
})()

By hovering over google sheet link we can click a link in a tooltip. there I want to prevent-default and send Href by chrome message to background script.and from there I can update tabs URL.

like image 871
NdmGjr Avatar asked Feb 18 '19 08:02

NdmGjr


Video Answer


1 Answers

Because the dom element is changing, when you listen here, the dom element will not be useful after the next update.

The solution is to use DOMSubtreeModified.

Below is my solution:

const stopURL = 'javascript:void(0)';
document.querySelector('#docs-editor-container').addEventListener('DOMSubtreeModified', event => {
  const aTags = event.path.filter(dom => dom.nodeName === 'A' && dom.className === 'waffle-hyperlink-tooltip-link');

  if (aTags.length === 0) return;

  aTags.forEach(a => {
    const oldHref = a.href;
    if (oldHref === stopURL) return;
    a.href = stopURL;
    console.log(oldHref);
  })
})

Now you can send oldHref to your extension and then operate from the extension.

It should be noted that this will trigger a CSP error, but it doesn't matter, this error will not affect the entire page and your extension.

As shown:

enter image description here

like image 141
Black-Hole Avatar answered Oct 10 '22 14:10

Black-Hole