我正在編寫我的第一個Chrome插件,我只想在當前網頁上顯示一些文本,並在點擊擴展名時將其顯示爲警報。假設我在一些搜索查詢後使用www.google.com上的任何網頁,Google會顯示「大約121,00,00,000個結果(0.39秒)」。我想在執行我的插件時將此文本顯示爲警報。這就是我正在做的。如何使用Chrome擴展程序訪問/讀取網頁上的任何文本/標記值
這裏要說的是,我使用
{
"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這裏是我的popup.js
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);
}
});
這裏是我的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);
}
});
感謝您的回覆。但我面臨兩個問題。 1)popup.js未執行。我剛剛添加了一個警報,即警報(「你好」);但它沒有執行。因此控制不會popup.js 2)即使我不去popup.js,並直接做到這一點, var a = document.getElementById(「resultStats」); alert(a.innerText); 雖然這個元素存在於谷歌搜索頁面 –
var a = document.getElementById(「resultStats」);返回null。 –