将数据从DOM传递到本机消息传递API

时间:2016-10-08 15:02:39

标签: javascript google-chrome-extension chrome-native-messaging

我正在处理Chrome扩展程序,该扩展程序通过Chrome的native messaging API将当前标签的网址发送到后台脚本。这将启动一个外部脚本,该脚本运行youtube-dl以提取视频URL并将其传递给在该平台上具有硬件加速的播放器。这是有效的,代码在这里:https://github.com/mad-ady/odroid.c2.video.helper

我想通过以下方式改进它:

  • 在每个视频元素之后在DOM中注入新按钮
  • 按钮按下提取视频元素的src URL并通过消息传递API将其传递给后端进行播放

我的问题是"这是允许的/可能的"? 当我在页面的范围内时如何调用后台定义的函数?

1 个答案:

答案 0 :(得分:1)

是的,你可以做那件事。

此外,如果您只需要从您的扩展程序处理单击按钮,您可以从content_script执行此操作而不将脚本注入页面(这是最安全的方式,因为您不会将任何内容附加到页面JS上下文)。

一步一步

manifest.json 中注册content_script和后台脚本:

...
"content_scripts": [
  {
    "matches": ["<all_urls>"],
    "js": ["content_script.js"]
  }
],
"background": {
  "scripts": ["background.js"]
},
...

将按钮添加到 content_script.js 中的共享DOM,并在content_script JS上下文中添加事件侦听器:

...
// You need to modify it for screen with video you want and for support old flash videos too
var blocks=document.getElementsByTagName("video");
for(i=0;i<blocks.length;i++){
  registerButton(blocks[i]);
}

// Add button and process click to it
function registerButton(block)
{
  var video=block;
  var button=document.createElement("input");
  button.type='button';
  button.class='getVideo';
  button.value='Send Video To the player';
  button.addEventListener('click',function(){sendUrlToBg(video.src);});
  blocks[i].parentNode.parentNode.parentNode.append(button);
}

// Send URL to background script
function sendUrlToBg(url)
{
    chrome.runtime.sendMessage({"action":"openBrowser","url":url},function(r){
        // process response from background script if you need, hide button, for example
    });
}
...

background.js 处理您的网址,将其发送到嵌入式应用,例如:

...
chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    if("action" in request && request.action == 'openBrowser'){
        // Send message to embeded app
        // ...
        // Send response for content script if you need
        sendResponse({"action":"openBrowserAnswer","status":"OK"});
    }
  }
);
....

多数民众赞成! :)

了解更多

  1. Chrome运行时sendMessage说明: https://developer.chrome.com/extensions/runtime#method-sendMessage
  2. Chrome消息:https://developer.chrome.com/extensions/messaging