内容脚本是 100% 的解决方案。
您基本上有两个单独的浏览器,常规浏览器和扩展弹出浏览器。但它们是完全独立的,只能来回发送消息。所以你需要做的是让扩展上下文向浏览器上下文发送一条消息,指示该上下文中的一些代码获取document.cookies
并将它们发送回扩展上下文。
这是我从每个单独的浏览器上下文中获取 cookie 的示例。
清单.json
{
"manifest_version": 2,
"name": "Cookie Monster",
"description": "Nom nom nom nom",
"version": "1.0",
"browser_action": {
"default_popup": "html/extension.html",
"default_title":"Cookie Monster"
},
"permissions": [
"activeTab",
"tabs",
"http://*/*",
"https://*/*"
],
"content_scripts": [{
"js":["/js/client.js"],
"matches":["http://*/*","https://*/*"]
}]
}
扩展名.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Cookies</title>
<style>
body {
display: block;
min-height: 250px;
width: 250px;
padding: 5px;
}
button {
display: block;
margin: 0 0 10px 0;
}
</style>
</head>
<body class="container">
<h1>Cookies</h1>
<button id="extension_cookies" type="button">Get PopUp Cookies</button>
<button id="browser_cookies" type="button">Get Browser Cookies</button>
<p id="result"></p>
<script src="/js/extension.js" type="text/javascript"></script>
</body>
</html>
扩展.js
'use strict';
(function(){
// cache import DOM elements
const extension_btn = document.querySelector('#extension_cookies');
const browser_btn = document.querySelector('#browser_cookies');
const result = document.querySelector('#result');
// runs in the popup window of the extension,
// which is it's own browser context
// and has it's own set of cookies
extension_btn.addEventListener('click', () => {
if (document.cookie === ''){
result.innerText = 'No Cookies...';
} else {
result.innerText = document.cookie;
}
})
// send message to browser context
// message will inform browser client of what to do
// the browser then needs to pass data to the callback function
// then we can display results
browser_btn.addEventListener('click', () => {
chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
chrome.tabs.sendMessage(tabs[0].id, {message: 'GET_COOKIES'}, (data) => {
result.innerText = data.cookies
});
});
})
}());
客户端.js
'use strict';
(function(){
// receive a callback function so I can pass data to extension
// get document cookies, put into an object
// use callback to send response to extension
const get_browser_cookies = (sendResponse) => {
const cookies = document.cookie;
console.clear();
console.log(cookies);
sendResponse({ cookies: cookies });
}
// listen for messages from extension
// a switch statement can help run only the correct function
// must pass the function a reference to the sendResponse function
// so I can pass data back to extension
chrome.runtime.onMessage.addListener(function(data_from_extension, sender, sendResponse){
switch (data_from_extension.message){
case 'GET_COOKIES': {
get_browser_cookies(sendResponse);
break;
}
default: null;
}
});
}())