Chrome扩展CORB:如何对共享DOM中的更新做出React

kb5ga3dv  于 2022-12-16  发布在  Go
关注(0)|答案(2)|浏览(151)

尝试构建一个chrome扩展内容脚本,为GitHub问题页面添加一个额外有用的导航。当通过普通网页进行交互时(最终用户点击一个React表情符号),我注入的元素丢失了。
我能够解决这个问题的唯一方法是设置一个间隔,该间隔不断地删除计数器元素并将其注入页面。
一定有比这更优雅的方法,允许对DOM更改做出响应,以便我可以删除并重新注入元素(而不是一直敲门)?
我尝试优化的扩展可以在这里找到
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

更新

我现在相信这个“bug”是由于CORB --这是一种针对Spectre的安全措施。
跨来源读取阻止(CORB)阻止了MIME类型为application/json的跨来源响应https://api.github.com/_private/browser/stats。有关详细信息,请参阅https://www.chromestatus.com/feature/5629709824032768
Google在他们的谈话Lessons from Spectre and Meltdown, and how the whole web is getting safer (Google I/O '18)中解释了更多
34:00中提到的示例似乎已被CORB阻止。

rnmwe5a2

rnmwe5a21#

由于GitHub会在第一个帖子中“最终用户点击了一个React表情符号”时替换整个#partial-discussion-sidebar节点,因此您需要在mutation observer响应中的addReactionNav()之前再次添加getWrapper(),如下所示。
更新:由于#partial-discussion-sidebar节点不会在第一个帖子以外的帖子更新时重新呈现,我们还需要对时间线项的更新做出响应。

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

mu0hgdu02#

如果当前选项卡已更新,您可以将消息传递回内容脚本以重新注入内容。
Background.js

chrome.tabs.onUpdated.addListener(tabId, changeInfo, tab) => {
  if (changeInfo.url) {
    chrome.tabs.sendMessage(tabId, {
      message: actions.TAB_UPDATED
    });
  }
})

Content.js

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.message === actions.TAB_UPDATED) {
    // show buttons
  }
});

相关问题