javascript - Chrome 扩展 CORB : How to react to updates in the shared DOM

标签 javascript google-chrome dom google-chrome-extension

尝试构建一个 chrome 扩展内容脚本,为 GitHub 问题页面添加一个额外有用的导航。当通过普通网页完成交互时(最终用户单击 react 表情符号) - 我注入(inject)的元素会丢失。

我能够解决它的唯一方法是设置一个间隔,不断删除我的计数器元素并将其注入(inject)页面。

一定有比这更优雅的方式来允许对 DOM 更改做出响应,这样我就可以删除并重新注入(inject)元素(而不是一直敲门)?

我正在尝试优化的扩展可以在这里找到

https://github.com/NorfeldtAbtion/github-issue-reactions-chrome-extension

重要文件目前看起来是这样的

addReactionsNav.js


const URL =
  window.location.origin + window.location.pathname + window.location.search
const header = document.querySelector('#partial-discussion-sidebar')
header.style = `position: relative;height: 100%;`
let wrapper = getWrapper()

// // The isolated world made it difficult to detect DOM changes in the shared DOM
// // So this monkey-hack to make it refresh when ..
// setInterval(() => {
//   wrapper.remove()
//   wrapper = getWrapper()
//   addReactionNav()
// }, 1000)

// Select the node that will be observed for mutations
const targetNode = document.querySelector('body')

// Options for the observer (which mutations to observe)
const config = { attributes: true, childList: true, subtree: true }

// Create an observer instance linked to the callback function
const observer = new MutationObserver(() => addReactionNav())

// Start observing the target node for configured mutations
observer.observe(targetNode, config)

function getWrapper() {
  const header = document.querySelector('#partial-discussion-sidebar')
  const wrapper = header.appendChild(document.createElement('div'))
  wrapper.style = `
      position:sticky;
      position: -webkit-sticky;
      top:10px;`
  return wrapper
}

function addReactionNav() {
  const title = document.createElement('div')
  title.style = `font-weight: bold`
  title.appendChild(document.createTextNode('Reactions'))
  wrapper.appendChild(title)

  // Grabbing all reactions Reactions �� �� �� �� ❤️ �� �� ��
  const reactionsNodes = document.querySelectorAll(`
    [alias="+1"].mr-1,
    [alias="rocket"].mr-1,
    [alias="tada"].mr-1,
    [alias="heart"].mr-1,
    [alias="smile"].mr-1,
    [alias="thinking_face"].mr-1,
    [alias="-1"].mr-1,
    [alias="eyes"].mr-1
  `)

  const reactionsNodesParents = [
    ...new Set(
      Array.from(reactionsNodes).map(node => node.parentElement.parentElement)
    ),
  ]

  reactionsNodesParents.forEach(node => {
    const a = document.createElement('a')
    const linkText = document.createTextNode('\n' + node.innerText)
    a.appendChild(linkText)
    a.title = node.innerText

    let id = null
    while (id == null || node != null) {
      if (node.tagName === 'A' && node.name) {
        id = node.name
        break
      }

      if (node.id) {
        id = node.id
        break
      }

      node = node.parentNode
    }
    const postURL = URL + '#' + id
    a.href = postURL
    a.style = `display:block;`

    wrapper.appendChild(a)
  })
}

manifest.json


{
  "manifest_version": 2,
  "name": "Github Issue Reactions",
  "version": "1.0",
  "description": "List a link of reactions on a github issue page",
  "permissions": ["https://www.github.com/", "http://www.github.com/"],
  "content_scripts": [
    {
      "matches": ["*://*.github.com/*/issues/*"],
      "js": ["addReactionsNav.js"],
      "run_at": "document_end"
    }
  ]
}

发现这个关于“孤立世界”的简短提及

https://youtu.be/laLudeUmXHM?t=79

更新

我现在相信“错误”是由于 CORB - 这是针对 Spectre 的安全措施。

Cross-Origin Read Blocking (CORB) blocked cross-origin response https://api.github.com/_private/browser/stats with MIME type application/json. See https://www.chromestatus.com/feature/5629709824032768 for more details.



谷歌在他们的谈话中解释了更多 Lessons from Spectre and Meltdown, and how the whole web is getting safer (Google I/O '18)

34:00 中提到的示例似乎从那以后就被CORB阻止了。

最佳答案

由于 GitHub 替换了整个 #partial-discussion-sidebar第一篇文章“最终用户点击 react 表情符号”时的节点,您需要getWrapper()再次在 addReactionNav() 之前在您的突变观察者响应中,如下所示。

更新:作为 #partial-discussion-sidebar如果不是第一个帖子的 react 更新,节点不会重新渲染,我们还需要响应时间线项目的更新。

const URL = window.location.origin + window.location.pathname + window.location.search;
const header = document.querySelector('#partial-discussion-sidebar');
header.style = `position: relative;height: 100%;`;
let wrapper = getWrapper();
addReactionNav();    // Initial display.

// Select the node that will be observed for mutations.
const targetNode = document.querySelector('body');

// Options for the observer (which mutations to observe).
const config = {
  childList: true,
  subtree: true
};

// Create an observer instance linked to the callback function.
const observer = new MutationObserver(mutations => {
  if (!targetNode.contains(wrapper) || mutations.some(mutation => mutation.target.matches('.js-timeline-item'))) {
    wrapper.remove();
    wrapper = getWrapper();
    addReactionNav();
  }
});

// Start observing the target node for configured mutations.
observer.observe(targetNode, config);

关于javascript - Chrome 扩展 CORB : How to react to updates in the shared DOM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59806062/

相关文章:

javascript - 当 base64 null 后跟 =? 时,HTML5 数据 URI 失败

javascript - 如何在chrome扩展中将popup.html调整为全屏

javascript - DOM 在我想要的地方添加表格行

javascript - 在附加元素上触发 CSS 过渡

javascript - 如何在 SweetAlert 弹出窗口中添加关闭按钮

javascript - Node Js Express 路由器不工作

google-chrome - Charles proxy - 如何在 Chrome 中使用 map 本地工具

javascript - <div> 标签有问题吗?

javascript - js中数组求和

javascript - 调用方法比从内存中检索内容更快