javascript - 如何从具有 chrome 扩展名的事件选项卡中获取段落?

标签 javascript google-chrome-extension

在我的 background.html 中,我得到了当前选项卡的 idurltitle像这样:

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

我还需要获取当前选项卡的第一段。这可能吗?我在 tab type 中没有看到任何相关内容.谢谢

更新

响应 serg's answer 的更新并从 here 复制代码:

这是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);
  });

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

更新

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"
  ]
}

更新

已插入 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***")
});

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

编辑

按照 serg 的建议编辑 background.html,“将所有需要它的代码包装到 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>

最佳答案

你不能从后台页面做到这一点,但你可以注入(inject) content script所有页面,并使用message passing按需将此信息传回后台页面。

关于javascript - 如何从具有 chrome 扩展名的事件选项卡中获取段落?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7733205/

相关文章:

ajax - 如何返回 AJAX 响应文本?

javascript - 仅显示一次字符串中的唯一字符

由于 'unsafe-eval',Chrome 扩展中的 Javascript Tensorflow 无法正常工作

javascript - Cordova Barcodescanner - 使用前置摄像头

javascript - 调整窗口大小时按类名触发调整文本区域大小

javascript - Safari 和 Chrome 上的 Tinymce 换行问题

javascript - Chrome 扩展 : Executing a script on every tab

javascript - 所有谷歌搜索页面的匹配模式

javascript - 是否允许在 chrome 扩展中使用 window.postMessage()?

javascript - 遍历选项卡以搜索字符串