chrome扩展开发之消息传递

// Message_Passing.js
// https://developer.chrome.com/extensions/messaging
// https://developer.chrome.com/extensions/messaging#examples
//  ***********************************************************************************************
// 一次性消息( one - time requests)
// 从content script发送给background:
chrome.runtime.sendMessage({
    cmd: "mycmd"
}, function(response) {
    console.log(response);
});
// 从background向content script发送消息:
chrome.tabs.query({
    active: true,
    currentWindow: true
}, function(tabs) {
    chrome.tabs.sendMessage(tabs[0].id, {
        cmd: "mycmd"
    }, function(response) {
        console.log(response);
    });
});
// 接收方代码:
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    console.log(sender.tab ? "from a content script:" + sender.tab.url : "from the extension");
    if (request.cmd == "mycmd")
        sendResponse("ok");
});
//  ***********************************************************************************************
// 长效消息( long - lived connections) 是现在消息的收发双方建立通道, 然后通过这个通道收发消息。
// 连接主动方:
var port = chrome.runtime.connect({
    name: "con1"
});
port.postMessage({
    cmd: "mycmd"
});
port.onMessage.addListener(function(msg) {
    if (msg.recmd == "remycmd ")
        port.postMessage({
            cmd: "mycmd2"
        });
    else if (msg.recmd == "remycmd2")
        port.postMessage({
            cmd: "mycmd3"
        });
});
// 连接被动方:
chrome.runtime.onConnect.addListener(function(port) {
    console.assert(port.name == "con1");
    port.onMessage.addListener(function(msg) {
        if (msg.cmd == "mycmd")
            port.postMessage({
                recmd: "remycmd"
            });
        else if (msg.cmd == "mycmd2")
            port.postMessage({
                recmd: "remycmd2"
            });
        else if (msg.cmd == "mycmd3")
            port.postMessage({
                recmd: "remycmd3"
            });
    });
});
//  ***********************************************************************************************
// 扩展间消息(cross-extension messages)是在不同的扩展之间收发消息。
// 同一扩展的不同组件
// For simple requests:
chrome.runtime.onMessageExternal.addListener(
    function(request, sender, sendResponse) {
        if (sender.id == blacklistedExtension)
            return; // don't allow this extension access
        else if (request.getTargetData)
            sendResponse({
                targetData: targetData
            });
        else if (request.activateLasers) {
            var success = activateLasers();
            sendResponse({
                activateLasers: success
            });
        }
    });

// For long-lived connections:
chrome.runtime.onConnectExternal.addListener(function(port) {
    port.onMessage.addListener(function(msg) {
        // See other examples for sample onMessage handlers.
    });
});
//  ***********************************************************************************************
// 从一个扩展到另一个扩展,需要传入扩展的Id作为参数
var laserExtensionId = "abcdefghijklmnoabcdefhijklmnoabc";

// Make a simple request:
chrome.runtime.sendMessage(laserExtensionId, {
        getTargetData: true
    },
    function(response) {
        if (targetInRange(response.targetData))
            chrome.runtime.sendMessage(laserExtensionId, {
                activateLasers: true
            });
    });

// Start a long-running conversation:
var port = chrome.runtime.connect(laserExtensionId);
port.postMessage(...);
//  ***********************************************************************************************
//从网页向扩展发送消息
// manifest.json
"externally_connectable": {
    "matches": ["*://*.example.com/*"]
}

// The ID of the extension we want to talk to.
var editorExtensionId = "abcdefghijklmnoabcdefhijklmnoabc";

// Make a simple request:
chrome.runtime.sendMessage(editorExtensionId, {
        openUrlInEditor: url
    },
    function(response) {
        if (!response.success)
            handleError(url);
    });
// 扩展监听来自网页的消息,similar to cross-extension messaging.
// via the runtime.onMessageExternal or runtime.onConnectExternal APIs
// 只能由web page方来初始化连接
chrome.runtime.onMessageExternal.addListener(
    function(request, sender, sendResponse) {
        if (sender.url == blacklistedWebsite)
            return; // don't allow this web page access
        if (request.openUrlInEditor)
            openUrl(request.openUrlInEditor);
    });
//  ***********************************************************************************************
// Native messaging
// 与注册为native-messaging-host的本地应用程序通信
// https://developer.chrome.com/extensions/nativeMessaging#native-messaging-host

// Security considerations 安全问题
// your background page should be careful not to fall victim to cross-site scripting
chrome.tabs.sendMessage(tab.id, {
    greeting: "hello"
}, function(response) {
    // WARNING! Might be evaluating an evil script!
    var resp = eval("(" + response.farewell + ")");
});
chrome.tabs.sendMessage(tab.id, {
    greeting: "hello"
}, function(response) {
    // WARNING! Might be injecting a malicious script!
    document.getElementById("resp").innerHTML = response.farewell;
});
// 使用安全API取代上面的脚本
chrome.tabs.sendMessage(tab.id, {
    greeting: "hello"
}, function(response) {
    // JSON.parse does not evaluate the attacker's scripts.
    var resp = JSON.parse(response.farewell);
});
chrome.tabs.sendMessage(tab.id, {
    greeting: "hello"
}, function(response) {
    // innerText does not let the attacker inject HTML elements.
    document.getElementById("resp").innerText = response.farewell;
});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值