Chrome扩展示例无效

时间:2017-07-05 19:05:06

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

我正在尝试创建Chrome扩展程序来解析当前网页的DOM中的某些数据。我发现了一些关于堆栈溢出的例子但没有一个能够工作。所有的例子都有几年了,所以我想知道最近是否对Chrome扩展进行了根本性的改变,这些改变使得很多这些例子都过时了。在这个特定的例子中,我收到一个警告 domContent = undefined ,并且无法找到console.log出现在我的控制台的任何位置。 原始问题在这里: Chrome Extension - Get DOM content

但我会粘贴代码以便于阅读:

background.js



// Regex-pattern to check URLs against. 
// It matches URLs like: http[s]://[...]stackoverflow.com[...]
var urlRegex = /^https?:\/\/(?:[^./?#]+\.)?stackoverflow\.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);
    }
});




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);
    }
});




的manifest.json



{
  "manifest_version": 2,
  "name": "Test Extension",
  "version": "0.0",

  "background": {
    "persistent": false,
    "scripts": ["background.js"]
  },
  "content_scripts": [{
    "matches": ["*://*.stackoverflow.com/*"],
    "js": ["content.js"]
  }],
  "browser_action": {
    "default_title": "Test Extension"
  },

  "permissions": ["activeTab"]
}




0 个答案:

没有答案