chrome.tabs.query没有被调用

时间:2019-05-26 01:58:44

标签: javascript google-chrome-extension

我对Chrome扩展方法有疑问。在我的popup.js消息中没有发送消息,因此在content.js中无法接收到消息,这使得该代码未被调用。

  

popup.js

document.addEventListener('DOMContentLoaded', function() {
  document.querySelector('button').addEventListener('click', onClick, false);
  document.querySelector('form').addEventListener('submit', e => e.preventDefault(), false);

  const blockedUsersContainer = document.querySelector('#blocked_users');

  function onClick () {
    const newUser = document.querySelector('form input').value;

    if(newUser.length > 0) {
      if(localStorage.getItem('blockedUsers') !== null) {
        let oldStorage = localStorage.getItem('blockedUsers'),
        newStorage = `${oldStorage},${newUser}`;
        localStorage.setItem('blockedUsers', newStorage);
      } else {
        localStorage.setItem('blockedUsers', newUser);
      }

        //this is string
        let blockedUser = localStorage.getItem('blockedUsers');

        //this function is not invoked.
        chrome.tabs.query({currentWindow: true, active: true}, function (tabs) {
          chrome.tabs.sendMessage(tabs[0].id, blockedUser);
        });
      }
    }
  }

  function setResponse({error, usersList}) {
    if(error) return alert(error);

    blockedUsersContainer.innerText = '';
    let blockedUsers = localStorage.getItem('blockedUsers');

    displayBlockedUsers(blockedUsers);
  }
}, false);
  

content.js

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  const commentsNodes = document.querySelectorAll('#komentarze dl');
  const newUserString = request.blockedUsers;

  sendResponse({error: false, usersList: newUserString})

  let usersListArray = newUserString.split(',');
  for (let i = 0; i < commentsNodes.length; i++) {
    for (let j = 0; j < usersListArray.length; j++) {
      if(commentsNodes[i].children[0].innerHTML.toLowerCase().includes(usersListArray[j].trim()))
      commentsNodes[i].style.display = 'none';
    }
  }
});

此代码有什么问题?为什么不调用该函数?我只是想不通...

0 个答案:

没有答案