如何使用Chrome扩展从活动选项卡中获取段落? [英] How to get a paragraph from the active tab with chrome extension?

查看:126
本文介绍了如何使用Chrome扩展从活动选项卡中获取段落?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

background.html 中,我得到了 id url title 这样的当前标签:

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

我还需要获取当前选项卡的第一段。这是可能的吗?我没有看到标签类型中的任何相关内容。谢谢



更新



更新回应 serg的答案并复制代码从这里



这是 dom.js

  chrome.extension.onRequest.addListener(function(request,sender,sendResponse){
if(request.action ==getDOM)
// sendResponse({dom:你想得到的dommmmm});
sendResponse({dom:document.getElementsByTagName(body)[0]});
// sendResponse({dom:document.getElementsByTagName(p)});
else
sendResponse({}); //不发送任何内容..
});

这就是我在 background.html

  //向内容脚本发送请求。 
chrome.tabs.sendRequest(tab.id,{action:getDOM},function(response){
console.log(response.dom);
});

但似乎没有任何事情发生。我甚至不知道在哪里寻找。



更新

  manifest.json:

{
name:My First Extension,
version:1.0,
description:我做的第一个扩展名,
background_page:background.html,
content_scripts:[
{
matches: [http:// * / *],
js:[dom.js]
}
],
browser_action:{
default_icon:icon.png
},
权限:[
标签,
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 - 请求操作)
sendResponse({dom:document.getElementsByTagName(body)[0]});
console.log(*** dom.js - sendResponse ***)
else
sendResponse({}); //不发送..
console.log(*** dom.js - else ***)
});

background.html

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

//发送请求到内容脚本。
chrome.tabs.sendRequest(tab.id,{action:getDOM},function(response){
console.log(response.dom);
console.log background - where 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)
// {
//向内容脚本发送请求
chrome.tabs.sendRequest(tab.id,{action:getDOM},function(response)
{
console.log(response .dom);
console.log(background - where response.dom)
//});将其移至包含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() 音调,这是一个音符);
//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 

函数(request,sender,sendResponse)
{
if(request.action ==getDOM)
{
console.log(dom.js - if(request.action == getDom))
// sendResponse({dom :你想得到的dommmmm});
// 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({} ); //不发送。
console.log(*** dom.js - else ***)
}
}
);

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

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

//发送请求到内容脚本。
chrome.tabs.sendRequest(tab.id,{action:getDOM},function(response){
// NOT SHOWING
console.log(response.dom)
//不显示
console.log(background - where response.dom)
});

tabId = tab.id;
//显示
console.log(tabId)
tabUrl = tab.url
//显示
console.log(tabUrl)
//显示
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。日志(请求200-OK);
chrome.browserAction.setBadgeText({text:done});
setTimeout(function(){
chrome.browserAction.setBadgeText({text:});
},2000);
} else {
//不显示
console.log(连接错误);
chrome.browserAction.setBadgeText({text:ERR});
}
}
};
xhr.send(formData);
// SHOWING
console.log(tabUrl:+ tabUrl)
// SHOWING
console.log(formData)

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


解决方案

你不能从背景页面,但是您可以向所有页面注入内容脚本,并使用消息传递将此信息传回后台页面。


In my background.html I am getting the id, url, and title of the current tab like this:

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

I also need to get the first paragraph of the current tab. Is this possible? I don't see anything related in the tab type. Thanks

Update

Update in response to serg's answer and copying the code from here:

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..
});

and this is what I have in background.html:

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

But nothing seems to be happenning. I don't even know where to look.

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

Inserted console.logs for debugging but I see none of them in the console; in fact dom.js does not even running, I misspelled "else" as "els" and no error was given. But otherwise the extension works well and executes the xhr request. What am I doing wrong?

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>

Edit

Edited background.html as suggested by serg "to wrap all code that needs it into chrome.tabs.sendRequest callback (all those xhrs)". But this version of the background does not work. I don't get any error messages but nothing happens. What am I doing wrong?

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

Update: Edited 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***")
        }
    }
);

Update with latest background.html with the console.logs that are showing marked:

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

解决方案

You can't do it from a background page, but you can inject content script to all pages, and use message passing to pass this info back to background page on demand.

这篇关于如何使用Chrome扩展从活动选项卡中获取段落?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆