私は最初のChromeプラグインを作成していますが、現在のウェブページにテキストを表示して、 。検索クエリの後にwww.google.comで任意のウェブページを使用しているとします。Googleは「約21,00,00,000件の結果(0.39秒)」を表示します。私はプラグインを実行するときにこのテキストを警告として表示したい。これは私がやっていることです。ここ Chrome拡張機能を使用してウェブページからテキスト/タグ値にアクセスする方法/読み込む方法
は、ここに私のpopup.jsである私は
{
"manifest_version": 2,
"name": "Getting started example",
"description": "This extension shows a Google Image search result for the current page",
"version": "1.0",
"background": {
"persistent": false,
"scripts": ["background.js"]
},
"content_scripts": [{
"matches": ["*://*.google.com/*"],
"js": ["content.js"]
}],
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": [
"activeTab"
]
}
を使用していますmanifest.jsonをあるここ
document.addEventListener('DOMContentLoaded', function() {
document.getElementById("checkPage").addEventListener("click", handler);
});`
function handler() {
var a = document.getElementById("resultStats");
alert(a.innerText); // or alert(a.innerHTML);
}
である私のcontent.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);
}
});
はここで**(拡張子のクリックで)
"content_scripts": [{
"run_at": "document_idle",
"matches"["*://*.google.com/*"],
"js": ["content.js"]
}],
2 "run_at" チェックを実行するために別のjsを作る私のbackground.js
var urlRegex = /^https?:\/\/(?:[^./?#]+\.)?google\.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);
}
});
返信いただきありがとうございます。私は2つの問題に直面しています。 1)popup.jsが実行されていません。私は警告を追加しました。つまり、警告(「こんにちは」)です。実行されていません。私はpopup.jsに行かなくてもこれを直接行っても、 var a = document.getElementById アラート(a.innerText); この要素はGoogle検索ページに存在しますが、これは何も表示されません –
var a = document.getElementById( "resultStats"); nullを返します。 –