如何使用Chrome扩展程序从网页访问/读取任何文本/标记值

时间:2016-08-24 04:40:16

标签: javascript google-chrome google-chrome-extension

我正在编写我的第一个Chrome插件,我只想在当前网页上显示一些文字,并在点击扩展程序时将其显示为提醒。假设我在使用www.google.com上的任何网页后搜索了一些搜索查询,Google会显示类似于"大约1,21,00,00,000个结果(0.39秒)" 。我想在执行插件时将此Text显示为警告。这就是我在做的事。

这是我正在使用的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);
}

这是我的内容.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 个答案:

答案 0 :(得分:0)

只需删除"default_popup"中的manifest.json部分,因为您已在后台页面中收听chrome.browserAction.onClicked个事件。他们无法同时生活。

相关问题