如何使用 Chrome 扩展从活动选项卡中获取段落?

2024-02-28

In my background.html我正在得到id, url, and title当前选项卡如下所示:

chrome.tabs.getSelected(null, function(tab) {
  tabId = tab.id;
  tabUrl = tab.url
  tabTitle = tab.title
  ...

我还需要获取当前选项卡的第一段。这可能吗?我没有看到任何相关内容tab type http://code.google.com/chrome/extensions/tabs.html#type-Tab. Thanks

Update

更新响应塞尔格的回答 https://stackoverflow.com/questions/7733205/how-to-get-a-paragraph-from-the-active-tab-with-chrome-extension/7734388#7734388并从中复制代码here https://stackoverflow.com/questions/1964225/accessing-current-tab-dom-object-from-popup-html/1964445#1964445:

This is dom.js:

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
 if (request.action == "getDOM")
   //sendResponse({dom: "The dommmmm that you want to get"});
   sendResponse({dom: document.getElementsByTagName("body")[0]});
   //sendResponse({dom: document.getElementsByTagName("p")});
 else
   sendResponse({}); // Send nothing..
});

这就是我所拥有的background.html:

  // Send a request to the content script.
  chrome.tabs.sendRequest(tab.id, {action: "getDOM"}, function(response) {
    console.log(response.dom);
  });

但似乎什么也没发生。我什至不知道去哪里看。

Update

manifest.json:

{
  "name": "My First Extension",
  "version": "1.0",
  "description": "The first extension that I made.",
  "background_page": "background.html",
  "content_scripts": [
     {
       "matches": ["http://*/*"],
       "js": ["dom.js"]
     }
   ],  
  "browser_action": {
    "default_icon": "icon.png"
  },
  "permissions": [
    "tabs",
    "http://ting-1.appspot.com/submithandlertest"
  ]
}

Update

插入console.logs进行调试,但我在控制台中看不到它们;事实上 dom.js 甚至没有运行,我将“else”错误拼写为“els”,并且没有给出错误。但除此之外,扩展程序运行良好并执行 xhr 请求。我究竟做错了什么?

dom.js

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
 if (request.action == "getDOM")
    console.log("dom.js - request action")
   sendResponse({dom: document.getElementsByTagName("body")[0]});
   console.log("***dom.js - sendResponse***")
 else
   sendResponse({}); // Send nothing..
   console.log("***dom.js - else***")
});

背景.html

<html>
<script>
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.getSelected(null, function(tab) {

  // Send a request to the content script.
  chrome.tabs.sendRequest(tab.id, {action: "getDOM"}, function(response) {
    console.log(response.dom);
    console.log("background -- where is response.dom")
  });

    tabId = tab.id;
    console.log(tabId)
    tabUrl = tab.url
    console.log(tabUrl)
    tabTitle = tab.title
    console.log(tabTitle)

var formData = new FormData();
formData.append("url", tabUrl);
formData.append("title", tabTitle);
formData.append("pitch", "this is a note");
//formData.append("user_tag_list", "tag1, tag2");


var xhr = new XMLHttpRequest();
xhr.open("POST", "http://ting-1.appspot.com/submithandlertest", true);
xhr.onreadystatechange = function (aEvt) {
    if (xhr.readyState == 4) {
        if (xhr.status == 200){ 
            console.log("request 200-OK");
            chrome.browserAction.setBadgeText ( { text: "done" } );
            setTimeout(function () {
            chrome.browserAction.setBadgeText( { text: "" } );
            }, 2000);
        }else{
            console.log("connection error");
            chrome.browserAction.setBadgeText ( { text: "ERR" } );
     }        
  }        
};
xhr.send(formData);
console.log("tabUrl: "+ tabUrl)
console.log(formData)

        });
    });
</script>
</html>

Edit

Edited background.html正如 serg 所建议的“将所有需要它的代码包装到chrome.tabs.sendRequest回调(所有这些 xhrs)”。但是这个版本的后台不起作用。我没有收到任何错误消息,但没有任何反应。我做错了什么?

<html>
    <script>
        chrome.browserAction.onClicked.addListener(function(tab) 
        {
            //chrome.tabs.getSelected(null, function(tab) 
            //{
            // Send a request to the content script.
            chrome.tabs.sendRequest(tab.id, {action: "getDOM"}, function(response) 
            {
                console.log(response.dom);
                console.log("background -- where is response.dom")
                //}); moving this down to include xhr
                tabId = tab.id;
                console.log(tabId)
                tabUrl = tab.url
                console.log(tabUrl)
                tabTitle = tab.title
                console.log(tabTitle)

                var formData = new FormData();
                formData.append("url", tabUrl);
                formData.append("title", tabTitle);
                formData.append("pitch", "this is a note");
                //formData.append("user_tag_list", "tag1, tag2");

//xhr*********************************************************************************        
                var xhr = new XMLHttpRequest();
                xhr.open("POST", "http://ting-1.appspot.com/submithandlertest", true);
                xhr.onreadystatechange = function (aEvt) 
                {
                    if (xhr.readyState == 4) 
                    {
                        if (xhr.status == 200)
                        { 
                            console.log("request 200-OK");
                            chrome.browserAction.setBadgeText ( { text: "done" } );
                            setTimeout(function () 
                            {
                                chrome.browserAction.setBadgeText( { text: "" } );
                            }, 2000);
                        }
                        else
                        {
                            console.log("connection error");
                            chrome.browserAction.setBadgeText ( { text: "ERR" } );
                        }        
                    }        
                };
                xhr.send(formData);
                console.log("tabUrl: "+ tabUrl)
                console.log(formData)
//xhr**********************************************************************************                
            }); //chrome.tabs.sendRequest
        });
    </script>
</html>

更新:编辑 dom.js:

chrome.extension.onRequest.addListener
(
    function(request, sender, sendResponse) 
    {
        if (request.action == "getDOM")
        {
            console.log("dom.js - if (request.action == getDom)")
            //sendResponse({dom: "The dommmmm that you want to get"});
            //sendResponse({dom: document.getElementsByTagName("body")[0]});

            sendResponse({dom: document.getElementsByTagName("p")[0]});
            console.log("***dom.js - sendResponse***")
            //var pageInfo = {
            //"title": document.title};
            //chrome.extension.sendRequest(pageInfo);
        }
        else
        {
            sendResponse({}); // Send nothing..
            console.log("***dom.js - else***")
        }
    }
);

使用最新的background.html更新console.log显示标记的:

<html>
<script>
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.getSelected(null, function(tab) {

  // Send a request to the content script.
  chrome.tabs.sendRequest(tab.id, {action: "getDOM"}, function(response) {
    //NOT SHOWING
    console.log(response.dom)
    //NOT SHOWING
    console.log("background -- where is response.dom")
  });

    tabId = tab.id;
    //SHOWING
    console.log(tabId)
    tabUrl = tab.url
    //SHOWING
    console.log(tabUrl)
    //SHOWING
    tabTitle = tab.title
    //SHOWING
    console.log(tabTitle)

var formData = new FormData();
formData.append("url", tabUrl);
formData.append("title", tabTitle);
formData.append("pitch", "this is a note");
//formData.append("user_tag_list", "tag1, tag2");

var xhr = new XMLHttpRequest();
xhr.open("POST", "http://ting-1.appspot.com/submithandlertest", true);
xhr.onreadystatechange = function (aEvt) {
    if (xhr.readyState == 4) {
        if (xhr.status == 200){
            //SHOWING 
            console.log("request 200-OK");
            chrome.browserAction.setBadgeText ( { text: "done" } );
            setTimeout(function () {
            chrome.browserAction.setBadgeText( { text: "" } );
            }, 2000);
        }else{
            //NOT SHOWING
            console.log("connection error");
            chrome.browserAction.setBadgeText ( { text: "ERR" } );
     }        
  }        
};
xhr.send(formData);
//SHOWING
console.log("tabUrl: "+ tabUrl)
//SHOWING
console.log(formData)

        });
    });
</script>
</html>

您无法从后台页面执行此操作,但可以注入内容脚本 http://code.google.com/chrome/extensions/dev/content_scripts.html到所有页面,并使用消息传递 http://code.google.com/chrome/extensions/dev/messaging.html按需将此信息传递回后台页面。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 Chrome 扩展从活动选项卡中获取段落? 的相关文章

随机推荐

  • Node JS - 将数据从 Busboy 流式传输到 AWS S3

    我正在尝试通过 ec2 将文件上传到 s3 我的第一个方法是 将文件完全上传到 ec2 然后将该文件上传到 s3 这种方法不好 因为从 ec2 到 s3 的传输时间是浪费时间 目前我正在尝试使用服务员上传流 to s3上传流这样上传到 ec
  • 使用 Boost Python 和 std::shared_ptr

    我正在尝试让 Boost Python 与 std shared ptr 很好地配合 目前 我收到此错误 Traceback most recent call last File test py line 13 in
  • C# 中强制垃圾回收的最佳实践

    根据我的经验 似乎大多数人都会告诉您强制垃圾收集是不明智的 但在某些情况下 您正在处理的大型对象并不总是在 0 代中收集 但内存是一个问题 是强制收集可以吗 有这样做的最佳实践吗 最佳实践是不强制进行垃圾回收 根据 MSDN 强制垃圾是可能
  • 谁能推荐一个Java富文本编辑器? [关闭]

    就目前情况而言 这个问题不太适合我们的问答形式 我们希望答案得到事实 参考资料或专业知识的支持 但这个问题可能会引发辩论 争论 民意调查或扩展讨论 如果您觉得这个问题可以改进并可能重新开放 访问帮助中心 help reopen questi
  • 使用 Cloud Endpoints 中的客户端库。 jar 导入不起作用

    我为我的 appengine python 应用程序创建了一个 jar 文件 我已按照以下步骤导入我的库 jar 文件这个例子 https developers google com appengine docs python endpoi
  • Java 中的最终变量操作

    谁能告诉我下面这行在 Java 上下文中的含义是什么 最终变量仍然可以是 被操纵 除非它是不可变的 据我所知 通过将任何变量声明为最终变量 您将无法再次更改它 那么它们的含义是什么不可变的在上面一行 这意味着如果您的最终变量是引用类型 即不
  • nginx:使用环境变量

    我有以下场景 我有一个环境变量 SOME IP已定义并希望在 nginx 块中使用它 参考Nginx 文档 http wiki nginx org CoreModule我用env指令中的nginx conf文件如下 user www dat
  • 媒体基金会 onReadSample 返回的样本大小错误

    我正在致力于将捕获库从 DirectShow 转换为 MediaFoundation 捕获库似乎工作得很好 但我在运行 Windows 8 32 位的平板电脑上遇到集成网络摄像头的问题 枚举捕获格式时 如中所述媒体基金会文档 http ms
  • Visual Studio 2013 中的调用目标引发了异常

    今天我打开的时候Visual Studio 2013 Professional Edition 我得到了错误exception has been thrown by a target of invocation 我也尝试打开ILSpy调试一
  • 更新 RDLC 报告中的数据源

    我正在使用 SQL 视图将数据传递到 RDLC 报告 现在 如果我向 SQL 视图添加一列 如何在 RDLC 报告中获取这个新添加的列 目前 我必须删除 RDLC 数据集并每次创建新的数据集 这根本不可行 希望有人有更好的方法来做到这一点
  • 通过ajax调用将文本加载到textarea中

    我想将从 dB 检索到的一些文本加载到文本区域中 用户点击一个链接 a class editlink href a JQuery 将 ID 传递给 GO PHP editlink click function get go php para
  • spring-data-jpa: ORA-01795: 列表中表达式的最大数量为 1000

    我正在使用 Spring Data JPA 我想从 a 获取 client id 的交易List
  • 修复 IE 错误:总是一个好主意吗? [关闭]

    Closed 这个问题是基于意见的 help closed questions 目前不接受答案 Internet Explorer 改进a lot在过去的 3 年里 自 IE 10 以来 IE 已经成为一个相当不错的浏览器 具有良好的性能
  • 如何将日期时间字符串转换为 UTC 以在 Highcharts 上绘制点

    我正在研究 HighCharts 样条不规则数据 这里数据传递为 data Date UTC 1970 9 27 0 Date UTC 1970 10 10 0 6 Date UTC 1970 10 18 0 7 Date UTC 1970
  • jQuery Draggable - 通过单击元素开始拖动元素,无需按住鼠标

    考虑一个基本的 jQuery Draggable 元素 有没有什么方法可以通过单击鼠标开始拖动元素 即 当元素被单击时 它进入拖动状态 并开始跟随鼠标 当再次单击时 它会掉落到原来的位置 如果这无法通过 jQuery 实现 那么是否可以通过
  • PHP启动:无法加载动态库

    我正在尝试使用 Firebird 2 5 2 26539 视窗8 阿帕奇2 2 22 PHP 5 4 10 当我在 php 中启用 firebird 扩展时 extension php interbase dll extension php
  • 如何安装 cython [重复]

    这个问题在这里已经有答案了 在Windows上安装Kivy的过程中 我发现我需要Cython 我尝试使用安装它easy install cython 但这给出了以下错误 error Unable to find vcvarsall bat
  • 年、月、日中 2 天之间的差异[重复]

    这个问题在这里已经有答案了 我需要输出年 月 日中两天的差值 通过时间跨度和减法 我只能得到天数 但是否有可能以年 月和日为单位输出 这是我到目前为止所拥有的 public string Leeftijdsverschil DateTime
  • 如何找到二值图像中的连通分量?

    我正在寻找一种算法来查找二进制图像中的所有连接组件 如果我们将图像视为矩阵 它看起来像 0 0 0 0 0 0 0 0 0 1 1 1 0 1 0 1 0 1 0 0 我想找到所有接触的 对角线的 以及 在此示例中 只有一个组件 但图像中可
  • 如何使用 Chrome 扩展从活动选项卡中获取段落?

    In my background html我正在得到id url and title当前选项卡如下所示 chrome tabs getSelected null function tab tabId tab id tabUrl tab ur