先交代一下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. });