将数据从DOM传递到本机消息传递API
Pass data from DOM to native messaging API
我正在研究一个chrome扩展,通过chrome的本地消息传递API将当前选项卡的URL发送到后台脚本。这将启动一个运行youtube-dl的外部脚本来提取视频url并将其传递给该平台上具有硬件加速的播放器。这是可行的,代码在这里:https://github.com/mad-ady/odroid.c2.video.helper.
我想改进一下:
- 在DOM中每个视频元素后注入新的按钮
- 按下按钮提取视频元素的src URL并通过消息传递API将其传递到后端进行播放
我的问题是"这是允许/可能的吗?"
当我在页面的作用域时,我如何调用在后台定义的函数?
是的,你可以那样做。
另外,如果你需要处理点击按钮只从你的扩展,你可以做到从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"});
}
}
);
....
这一切!:)
阅读更多
- Chrome运行时sendMessage描述:https://developer.chrome.com/extensions/runtime method-sendMessage
- Chrome消息:https://developer.chrome.com/extensions/messaging
相关文章:
- '图片'没有用于本机道具的propType'RCTImageView.overlayColor&
- 在iOS和Android上使用React native时,我还能使用本机第三方lirbraries吗
- javascript函数访问ios本机功能
- 如何在从客户端接收数据时从本机方法触发javascript函数?
- 在浏览器中检测本机或第三方PDF插件
- 将事件发送到javascript文档的react本机模块是否正确
- 将对应用内购买的支持构建为react本机代码
- 如何在Windows上用javascript构建本机应用程序
- 在视图中渲染多个按钮以编程方式进行本机反应
- 如何将chrome.tabCapture流从js传递到c++PNACL本机代码
- 为什么我得到Chrome本机消息“;找不到指定的本机消息传递主机&”;
- 为Chrome扩展指定本机消息主机
- 使用 JS-ctypes 将结构化数据传递给本机代码
- 从列表视图传递 React 本机状态
- 将数据从DOM传递到本机消息传递API
- javascript将字符串传递给本机objective-c
- Java和chrome扩展,本机消息
- 使用本机javascript传递事件侦听器参数
- 当“循环”时,不能在本机承诺之间传递数据;他们
- 用于调用外部应用程序的NPAPI替换(本机消息传递主机)无法工作