gpt4 book ai didi

javascript - 将数据从 DOM 传递到 native 消息传递 API

转载 作者:行者123 更新时间:2023-12-03 05:55:49 25 4
gpt4 key购买 nike

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

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

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

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

最佳答案

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

此外,如果您只需要从扩展程序处理对按钮的点击,您可以从 content_script 执行此操作,而无需将脚本注入(inject)到页面(这是最安全的方法,因为您不会将任何内容附加到页面 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

关于javascript - 将数据从 DOM 传递到 native 消息传递 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39933888/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com