ポップアップからactiveTabのDOMコンテンツにアクセスしようとしています。これが私のマニフェストです。
{
"manifest_version": 2,
"name": "Test",
"description": "Test script",
"version": "0.1",
"permissions": [
"activeTab",
"https://api.domain.com/"
],
"background": {
"scripts": ["background.js"],
"persistent": false
},
"content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",
"browser_action": {
"default_icon": "icon.png",
"default_title": "Chrome Extension test",
"default_popup": "index.html"
}
}
バックグラウンドスクリプト(persistence: falseのイベントページ)とcontent_scriptsのどちらが良いのか、とても迷っています。ドキュメントや他の方の投稿をすべて読みましたが、いまだに意味がわかりません。
どなたか、なぜどちらかを使うべきなのか説明してください。
試しに作ってみたbackground.jsは以下の通りです。
chrome.extension.onMessage.addListener(
function(request, sender, sendResponse) {
// LOG THE CONTENTS HERE
console.log(request.content);
}
);
そして、これをポップアップコンソールから実行しています。
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.sendMessage(tab.id, { }, function(response) {
console.log(response);
});
});
を取得しています。
Port: Could not establish connection. Receiving end does not exist.
UPDATE:
{
"manifest_version": 2,
"name": "test",
"description": "test",
"version": "0.1",
"permissions": [
"tabs",
"activeTab",
"https://api.domain.com/"
],
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"]
}
],
"content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",
"browser_action": {
"default_icon": "icon.png",
"default_title": "Test",
"default_popup": "index.html"
}
}
content.js
chrome.extension.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.text && (request.text == "getDOM")) {
sendResponse({ dom: document.body.innertHTML });
}
}
);
popup.html
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.sendMessage(tab.id, { action: "getDOM" }, function(response) {
console.log(response);
});
});
実行してみると、やはり同じエラーが出ます。
undefined
Port: Could not establish connection. Receiving end does not exist. lastError:30
undefined
Google Chrome Extensions Documentation]1**を参照してください。
コンテンツスクリプトとバックグラウンドページのどちらが良いかというご質問ですが。
コンテンツスクリプト:間違いありません。 コンテンツスクリプトは、WebページのDOMにアクセスできる拡張機能の唯一のコンポーネントです。
**バックグラウンドページ/ポップアップ多分(2つのうち最大1つ) コンテンツスクリプトは、DOMコンテンツをバックグラウンドページまたはポップアップに渡して処理を行う必要があるかもしれません。
繰り返しになりますが、入手可能なドキュメントをより注意深く研究することを強くお勧めします。
そこで、StackOverflow ページの DOM コンテンツを取得して背景ページに送り、コンソールに表示する拡張機能のサンプルを紹介します。
background.js:
// Regex-pattern to check URLs against.
// It matches URLs like: http[s]://[...]stackoverflow.com[...]
var urlRegex = /^https?:\/\/(?:[^./?#]+\.)?stackoverflow\.com/;
// A function to use as callback
function doStuffWithDom(domContent) {
console.log('I received the following DOM content:\n' + domContent);
}
// When the browser-action button is clicked...
chrome.browserAction.onClicked.addListener(function (tab) {
// ...check the URL of the active tab against our pattern and...
if (urlRegex.test(tab.url)) {
// ...if it matches, send a message specifying a callback too
chrome.tabs.sendMessage(tab.id, {text: 'report_back'}, doStuffWithDom);
}
});
コンテンツ.js:
// Listen for messages
chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
// If the received message has the expected format...
if (msg.text === 'report_back') {
// Call the specified callback, passing
// the web-page's DOM content as argument
sendResponse(document.all[0].outerHTML);
}
});
manifest.json:
{
"manifest_version": 2,
"name": "Test Extension",
"version": "0.0",
...
"background": {
"persistent": false,
"scripts": ["background.js"]
},
"content_scripts": [{
"matches": ["*://*.stackoverflow.com/*"],
"js": ["content.js"]
}],
"browser_action": {
"default_title": "Test Extension"
},
"permissions": ["activeTab"]
}
メッセージパッシングを使ってDOMを取得したり変更したりする必要はありません。私は代わりに chrome.tobs.executeScript
を使いました。私の例では、activeTabパーミッションのみを使用しているので、スクリプトはアクティブなタブ上でのみ実行されます。
マニフェスト.jsonの部分
"browser_action": {
"default_title": "Test",
"default_popup": "index.html"
},
"permissions": [
"activeTab",
"<all_urls>"
]
index.htmlの部分
<!DOCTYPE html>
<html>
<head></head>
<body>
<button id="test">TEST!</button>
<script src="test.js"></script>
</body>
</html>
test.js
document.getElementById("test").addEventListener('click', () => {
console.log("Popup DOM fully loaded and parsed");
function modifyDOM() {
//You can play with your DOM here or check URL against your regex
console.log('Tab script:');
console.log(document.body);
return document.body.innerHTML;
}
//We have permission to access the activeTab, so we can call chrome.tabs.executeScript:
chrome.tabs.executeScript({
code: '(' + modifyDOM + ')();' //argument here is a string but function.toString() returns function's code
}, (results) => {
//Here we have just the innerHTML and not DOM structure
console.log('Popup script:')
console.log(results[0]);
});
});