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

Pass data from DOM to native messaging API

我正在开发一个 chrome 扩展,它通过 Chrome 的 native messaging API. This starts an external script which runs youtube-dl to extract the video url and pass it to a player that has hardware acceleration on that platform. This works and the code is here: https://github.com/mad-ady/odroid.c2.video.helper 将当前选项卡的 URL 发送到后台脚本。

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

我的问题是"is this allowed/possible"?
当我在页面范围内时,如何调用在后台定义的函数?

是的,你可以做到这一点。

此外,如果您只需要从您的扩展程序处理对按钮的点击,您可以从 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中处理您的URL,将其发送到嵌入式应用程序,例如:

...
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