我正在编写我的第一个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。 –