【问题标题】:Chrome extension message passing is not working?Chrome 扩展消息传递不起作用?
【发布时间】:2019-07-24 07:21:59
【问题描述】:

contentScript.js 中没有调用该函数。

background.js

var insertUI = true
// var hasExecutedOnce = false

chrome.browserAction.onClicked.addListener(function(tab) {
  console.log(`clicked browserAction`)

  // if (!hasExecutedOnce)
  chrome.tabs.executeScript(tab.id, {
    file: 'contentScript.js',
  })

  chrome.runtime.sendMessage({
    from: 'background',
    subject: insertUI ? 'insertUI' : 'removeUI',
  })

  chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.subject === 'doneRemovingUI') insertUI = false
    else if (request.subject === 'doneInsertingUI') insertUI = true
  })

  insertUI = !insertUI
  // hasExecutedOnce = true
})

console.log(`bg`)

manifest.json

{
  "manifest_version": 2,
  "name": "Sample",
  "version": "1.0.0",
  "description": "Sample Extension",
  "icons": {
    "16": "icon16.png",
    "19": "icon19.png",
    "24": "icon24.png",
    "32": "icon32.png",
    "38": "icon38.png",
    "48": "icon48.png",
    "64": "icon64.png",
    "128": "icon128.png"
  },
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },
  "browser_action": {
    "default_icon": {
      "19": "icon19.png",
      "38": "icon38.png"
    }
  },
  "permissions": ["activeTab", "<all_urls>"]
}

contentScript.js

var body = document.getElementsByTagName('body')[0]

function insertUI() {
  console.log(`insertUI`)

  var div = document.createElement('div')
  div.setAttribute('id', 'sample-extension-12345')
  div.innerHTML = `<h1>Sample Extension</h1>`
  body.appendChild(div)
}

function removeUI() {
  console.log(`removeUI`)

  var divId = document.getElementById('sample-extension-12345')
  body.removeChild(divId)
}

function main() {
  console.log(`main called`)

  chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
    console.log({ msg, sender, sendResponse })

    if (msg.subject === 'insertUI') {
      insertUI()
      sendResponse({
        from: 'content',
        subject: 'doneInsertingUI',
      })
    } else if (msg.subject === 'removeUI') {
      removeUI()
      sendResponse({
        from: 'content',
        subject: 'doneRemovingUI',
      })
    }
  })
}
console.log(`contentScript`)

main()

所以一切正常。 insertUI() & removeUI()contentScript.js 中单独工作,但 chrome.runtime.onMessage.addListener 永远不会被调用。

其中的console.log() 未被调用。休息一切正常。插入 DOM 和删除 DOM 是分开工作的。他们只需要在切换browser_action 时工作。

【问题讨论】:

  • 要将消息从后台脚本发送到内容脚本,您必须使用chrome.tabs.sendMessage,而不是chrome.runtime.sendMessage。此外,您必须在内容脚本运行后发送消息,即在chrome.tabs.executeScript 的回调函数中。最后是分号。
  • 所以我按照您的要求更改了所有内容,并且可以正常工作。但是,现在我遇到了从 DOM 中多次插入和删除的问题,因为 executeScript 每次单击 browser_action 时都会添加脚本。我该如何解决这个问题?这是完整的要点gist.github.com/deadcoder0904/ac26007a86e3a57846125446bf6c5227
  • @IvánNokonoko 我也添加了解决方案作为答案,尽管从技术上讲它有自己的问题。也请检查下面的答案,因为我添加了不起作用的屏幕截图。它还不断在 DOM 中添加节点并删除它们。如果你知道如何解决这个问题,那会很有帮助:)
  • 好的,终于找到了一个完美的解决方案。将其发布为答案:)

标签: javascript google-chrome-extension firefox-addon browser-extension


【解决方案1】:

Iván Nokonoko 在 cmets 中回答了上述问题。为简洁起见在这里发布 -

background.js

var hasExecutedOnce = false

function addUI(tabId) {
  chrome.tabs.sendMessage(tabId, {
    from: 'background',
    subject: 'isUIAdded?',
  })
}

chrome.browserAction.onClicked.addListener(function(tab) {
  if (!hasExecutedOnce) {
    chrome.tabs.executeScript(
      tab.id,
      {
        file: 'contentScript.js',
      },
      function() {
        addUI(tab.id)
      },
    )
    hasExecutedOnce = true
  }
  addUI(tab.id)
})

manifest.json

{
  "manifest_version": 2,
  "name": "Sample",
  "version": "1.0.0",
  "description": "Sample Extension",
  "icons": {
    "16": "icon16.png",
    "19": "icon19.png",
    "24": "icon24.png",
    "32": "icon32.png",
    "38": "icon38.png",
    "48": "icon48.png",
    "64": "icon64.png",
    "128": "icon128.png"
  },
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },
  "browser_action": {
    "default_icon": {
      "19": "icon19.png",
      "38": "icon38.png"
    }
  },
  "permissions": ["activeTab", "<all_urls>"]
}

contentScript.js

var body = document.getElementsByTagName('body')[0]

function insertUI() {
  var div = document.createElement('div')
  div.setAttribute('id', 'sample-extension-12345')
  div.innerHTML = `<h1>Sample Extension</h1>`
  body.appendChild(div)
}

function removeUI() {
  document.getElementById('sample-extension-12345').remove()
}

function main() {
  chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.subject === 'isUIAdded?') {
      const id = document.getElementById('sample-extension-12345')
      if (id === null) insertUI()
      else removeUI()
    }
  })
}

main()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-01
    • 1970-01-01
    • 2015-11-27
    • 2021-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多