如何在Chrome扩展程序的内容脚本中将事件监听器添加到Google表格链接? [英] How can I add event Listener to google sheets link in chrome extension's content script?

查看:128
本文介绍了如何在Chrome扩展程序的内容脚本中将事件监听器添加到Google表格链接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发chrome扩展程序,以打开从不同列到其指定标签的链接. 使用 Google Apps脚本API 在chrome扩展程序内部创建工作表的上下文.但是 Google Apps脚本API 是一条很长的路,我无法避免在单击链接表单时打开和关闭选项卡.

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.

以下是(内容脚本)中的代码.与链接相关.

(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')
  }
})()

通过将鼠标悬停在Google表格链接上,我们可以单击工具提示中的链接. 在那里,我要阻止默认设置,并通过chrome消息将Href发送到后台脚本.从那里,我可以更新标签的URL.

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.

推荐答案

由于dom元素正在更改,因此当您在此处收听时,dom元素在下一次更新后将不再有用.

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

解决方案是使用DOMSubtreeModified.

The solution is to use DOMSubtreeModified.

以下是我的解决方法:

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);
  })
})

现在,您可以将oldHref发送到您的扩展程序,然后从该扩展程序进行操作.

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

应注意,这将触发CSP错误,但没关系,该错误不会影响整个页面和您的扩展名.

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.

如图所示:

这篇关于如何在Chrome扩展程序的内容脚本中将事件监听器添加到Google表格链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆