chrome扩展程序获取当前页面URL和HTML内容

先交代一下manifest.json中的配置

// 引入注入脚本
"content_scripts": [
{
"js": ["content_script.js"],
// 在什么情况下使用该脚本
"matches": [
"http://*/*",
"https://*/*"
],
// 什么情况下运行【文档加载开始】
"run_at": "document_start"
}
],
{
"permissions": [ "tabs"]
}

1.获取当前页面的URL

可在popup.js中获取(chrome.tabs.getCurrent已经out了,返回值是undefined)

    chrome.tabs.getSelected(null, function (tab) {
        console.log(tab.url);
    });

2.获取当前页面的HTML内容

content-script.js 是注入标签页内的脚本
popup.js 是弹出框脚本
 
相互通信的方式 sendMessage(msg, callback)、 onMeassage(callback)(sendRequest、onRequest已经out了,API不再支持)
popup.js:发送消息
chrome.tabs.getSelected(null, function (tab) {  // 先获取当前页面的tabID
chrome.tabs.sendMessage(tab.id, {greeting: "hello"}, function(response) {
console.log(response);  // 向content-script.js发送请求信息
});
});
content-script.js:响应消息
   var html = document.body.innerHTML;
    chrome.extension.onMessage.addListener(
        function(request, sender, sendMessage) {if (request.greeting == "hello")
                sendMessage(html);
            else
                sendMessage("FUCK OFF"); // snub them.
        });
 
 

转载于:https://www.cnblogs.com/hjqbit/p/7260110.html

  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值