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