我正在写我的第一个Chrome插件,我只是想得到一些文本,在当前的网页上,并显示作为警报,当我点击扩展。假设我在www.google.com上使用任何一个网页,经过一些搜索查询后,谷歌会显示“大约1,210万,00000个结果(0.39秒)”。当我执行插件时,我想以警告的形式显示这段文字。这就是我要做的。
这里是我正在使用的manifest.json
{
"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"
]
}这里是我的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);
}
});发布于 2016-08-24 05:13:31
1)在文档就绪后运行内容说明**检查"run_at“
"content_scripts": [{
"run_at": "document_idle",
"matches"["*://*.google.com/*"],
"js": ["content.js"]
}],2)单击扩展,使另一个js运行(弹出js)。弹出js可以访问(打开的页面文档)。
// A function to use as callback
function doStuffWithDom() {
//console.log('I received the following DOM content:\n' + domContent);
//get tabID when browser action clicked @ tabId = tab.id
chrome.tabs.executeScript(tabId, {file: "js/popup.js"});
}3)在弹出JS中,您可以设置警报
var a = document.getElementById("resultStats");
alert(a.innerText); // or alert(a.innerHTML);发布于 2016-08-24 05:45:28
只需在"default_popup"页面中删除manifest.json中的chrome.browserAction.onClicked部件,因为您已经在后台页面中收听了chrome.browserAction.onClicked事件。他们不能同时生活。
https://stackoverflow.com/questions/39114541
复制相似问题