从网页调用background.js函数

时间:2016-03-20 15:47:06

标签: javascript google-chrome-extension postmessage

我在background.js有一个功能

function cookielog()
{
chrome.cookies.getAll({},function(c){console.log(c);});
}

我想从任何网页上调用此cookielog

我见过这个

sending message to chrome extension from a web page

但它对我不起作用,我收到此错误

attempting to use a disconnected port object

在我的网页上执行js

var customEvent = document.createEvent('Event');
customEvent.initEvent('cookieyolla', true, true);
function fireCustomEvent(data) {
    hiddenDiv = document.getElementById('cookieyolla');
    hiddenDiv.innerText = data;
    hiddenDiv.dispatchEvent(customEvent);
}
fireCustomEvent(5);

background.js

chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
if (tab.url.indexOf('http') == '0' && changeInfo.status == 'complete') {
    try {
        chrome.tabs.executeScript(tabId, {
            code: 'if(typeof onceworked==\'undefined\'){var onceworked=true;var port=chrome.extension.connect();port.onMessage.addListener(function(msg){if(msg.message==\'cookieyolla\'){setTimeout(function(){alert(\'sik beni\');chrome.cookies.getAll({},cookielog);},msg.values*1000);}});var iDiv=document.createElement(\'div\');iDiv.id=\'cookieyolla\';iDiv.style.display=\'none\';document.getElementsByTagName(\'body\')[0].appendChild(iDiv);document.getElementById(\'cookieyolla\').addEventListener(\'cookieyolla\',function(){port.postMessage({message:\'cookieyolla\',values:document.getElementById(\'cookieyolla\').innerText});});};',
            allFrames: true,
            runAt: 'document_end'
        });
    } catch (e) {
    }
}

});

我做错了什么?

if (typeof onceworked == 'undefined') {
    var onceworked = true;
    var port = chrome.extension.connect();
    port.onMessage.addListener(function (msg) {
        if (msg.message == 'cookieyolla') {
            setTimeout(function () {
                alert('sik beni');
                chrome.cookies.getAll({}, cookielog);
            }, msg.values * 1000);
        }
    });
    var iDiv = document.createElement('div');
    iDiv.id = 'cookieyolla';
    iDiv.style.display = 'none';
    document.getElementsByTagName('body')[0].appendChild(iDiv);
    document.getElementById('cookieyolla').addEventListener('cookieyolla', function () {
        port.postMessage({
            message : 'cookieyolla',
            values : document.getElementById('cookieyolla').innerText
        });
    });
};

代码:“”格式化部分

最好的问候

1 个答案:

答案 0 :(得分:0)

@Mustafa,你应该阅读long-live connection

  

有时,对话的持续时间超过单个请求和响应非常有用。在这种情况下,您可以分别使用 runtime.connect tabs.connect 打开从内容脚本到扩展页面的长期通道,反之亦然。通道可以选择使用名称,以便您区分不同类型的连接。

另外,请尝试使用Dev Tools。这将有助于您暂停对未捕获的错误/异常的操作。