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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM