如何有效地在background.js,content.js和popup.html之间进行通信?

时间:2018-12-08 02:13:58

标签: javascript mutation-observers

我正在尝试进行chrome扩展,以从先前打开的特定网页中获取所有数据,并将该数据发送到单独的窗口,在这种情况下,我使用自己的页面,因为我无法解决其他解决方案。问题是我遇到了一个我不知道如何解决的错误。

我的设置如下:我将在弹出窗口中单击一个按钮,然后background.js中的脚本将获取所有符合我要求的所需浏览器窗口,并将其分类以安排如何从中收集数据将显示在单独的窗口中。然后,对于每个打开的页面,脚本将使用mutationObservers检测其中的更改,所有这些都将进入单独的窗口。到目前为止,我已经知道了,我能够从executer.js获取数据,然后将其传递给background.js,当我尝试将其传递给单独的窗口(fabricioyacques.tech)时,出现此错误:

  

runtime.onMessage事件处理程序中的错误:错误:调用   表格tabs.connect(object)与定义不匹配   tabs.connect(整数tabId,可选对象connectInfo)       在

如果您能给我有关我可以使用什么以及如何使用它的建议,我将不胜感激,文档并没有真正说明在诸如此类的特定情况下该使用什么。

executer.js

var config = {characterData : true, childList : true}
var configMatchStarted = {attributes: true, childList: true, characterData: true, subtree: true };
//var configMarkets = {attributes: true, childList: true, characterData: true, subtree: true };
var scoreboard = document.getElementsByClassName("counter-number player1")

if(scoreboard.length > 0) {

    console.log("Match has already started.");
    matchStart(true);

} else {

var period = document.getElementById("scoreboard"); 
var observerMatchStart = new MutationObserver(function(mutations){
    matchStart(false)
});

observerMatchStart.observe(period, configMatchStarted);

console.log("match has not started yet")

}


function matchStart(status) {
    if (status == false) {
        observerMatchStart.disconnect()
        console.log('Observer Match Start disconnect')
    } 
    //setting up the score observer
    var homeTeam = document.getElementsByClassName("counter-number player1");
    var awayTeam = document.getElementsByClassName("counter-number player2");
    var teamObservers = new MutationObserver(checkGoal)

    teamObservers.observe(homeTeam[0], config)
    teamObservers.observe(awayTeam[0], config)
    redBackground(true)
    //setting up the markets observer
    //var market = document.getElementsByClassName('marketboard rounded-bottom') 
    //var marketsObserver = new MutationObserver(marketsClosed)
    //marketsObserver.observe(market[0], configMarkets)
}

function redBackground() {

    if(document.getElementById("event").classList.add("red-background")){console.log('rojo')}else {console.log('no funcina')};

    var time = new Date();
    var hours = time.getHours()
    var minutes = time.getMinutes()
    var seconds = time.getSeconds()
    if (hours < 10) {hours = "0" + hours}
    if (minutes < 10) {minutes = "0" + minutes}
    if (seconds < 10) {seconds = "0" + seconds}

    var marketTime =
    hours + ":" 
    + minutes + ":"
    + seconds + "  "
    + document.getElementsByClassName("participantName name")[0].textContent + " "
    + document.getElementsByClassName("counter-number player1")[0].textContent + ":"
    + document.getElementsByClassName("counter-number player2")[0].textContent + " "
    + document.getElementsByClassName("participantName name")[1].textContent;

    console.log(marketTime)

    setTimeout(function() {
        document.getElementById("event").classList.remove("red-background")
    }, 10000)

    chrome.runtime.sendMessage({
    'sentBwinText': true,
    'logs' : marketTime,
    'red' : true
    });
}

function checkGoal(mutationList) {
    mutationList.forEach((mutation) => {
        if(mutation.type == 'childList') {
            if (mutation.addedNodes.length == '0') {
            redBackground()
            }       
        }           
    })              
}           


function marketsClosed(mutationList) {
  mutationList.forEach((mutation) => {
    switch(mutation.type) {
        case 'attributes':


        break;
    }
  });
}

background.js

chrome.runtime.onMessage.addListener(function(message, sender) {

    if(message.openBwin == true) {

        chrome.tabs.executeScript({
            file: 'executer.js'
        });  
        chrome.tabs.create({ url: "https://fabricioyacques.tech/sportradar-extension/"} , function(tab) {
tabId = tab.id

} );



    } 


        if(message.sentBwinText == true && message.logs){

            console.log(tabId)

        var port = chrome.tabs.connect({tabId, name: "data"});

            console.log(message.logs)

            var logsToSend = message.logs
            if(logsToSend) {
                port.postMessage({sendingLogs: "'" + logsToSend + "'"})
            } else {
                console.log('mensajes no mandados')
            }
            port.postMessage({red: true})

        }




});

content.js

var port = chrome.runtime.connect({name: "data"});
chrome.runtime.onConnect.addListener(function(port) {
    console.log('logsToSend')   
    port.onMessage.addListener(function(msg) {
        if(msg.sendingLogs){
        console.log(msg.sendingLogs)
            if(msg.red){
    if(document.getElementById("event").classList.add("red-background")){console.log('rojo')}else {console.log('no anda')};
    }

    }}) 
})

popup.js

document.getElementById("bwin").addEventListener("click", function(e) {
    chrome.runtime.sendMessage({'openBwin': true});
});

manifest.json

{
    "manifest_version": 2,
    "name": "Bet Monitoring Helper",
    "version": "0.1",
    "permissions": [ "activeTab", "tabs", "http://*/*", "https://*/*" ],
    "content_scripts":  [
        {
            "matches": [
                "https://fabricioyacques.tech/sportradar-extension/"
            ],
            "js":  ["jquery-3.3.1.min.js","content.js"],
            "css": [ "styles.css" ]

        }
    ],
    "background": {
        "scripts": ["background.js" , "executer.js"],
        "persistent": false
    },
    "browser_action": {
        "default_icon": "seven.png",
        "default_popup": "popup.html"
    },
    "externally_connectable": {
        "matches": ["https://fabricioyacques.tech/sportradar-extension/"]
      }
}

0 个答案:

没有答案