首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Chrome扩展-获取DOM内容

Chrome扩展-获取DOM内容
EN

Stack Overflow用户
提问于 2013-11-04 04:57:06
回答 3查看 196.6K关注 0票数 139

我正在尝试从弹出窗口访问activeTab DOM内容。这是我的清单:

{
  "manifest_version": 2,

  "name": "Test",
  "description": "Test script",
  "version": "0.1",

  "permissions": [
    "activeTab",
    "https://api.domain.com/"
  ],

  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },
  "content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",

  "browser_action": {
    "default_icon": "icon.png",
    "default_title": "Chrome Extension test",
    "default_popup": "index.html"
  }
}

我真的很困惑后台脚本(具有持久性的事件页面: false)还是content_scripts是可行的方法。我已经阅读了所有的文档和其他SO帖子,但对我来说仍然没有任何意义。

谁能解释一下为什么我可能会用一个而不是另一个。

这是我一直在尝试的background.js:

chrome.extension.onMessage.addListener(
  function(request, sender, sendResponse) {
    // LOG THE CONTENTS HERE
    console.log(request.content);
  }
);

我只是从弹出控制台执行以下操作:

chrome.tabs.getSelected(null, function(tab) {
  chrome.tabs.sendMessage(tab.id, { }, function(response) {
    console.log(response);
  });
});

我得到了:

Port: Could not establish connection. Receiving end does not exist. 

更新:

{
  "manifest_version": 2,

  "name": "test",
  "description": "test",
  "version": "0.1",

  "permissions": [
    "tabs",
    "activeTab",
    "https://api.domain.com/"
  ],

  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content.js"]
    }
  ],

  "content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",

  "browser_action": {
    "default_icon": "icon.png",
    "default_title": "Test",
    "default_popup": "index.html"
  }
}

content.js

chrome.extension.onMessage.addListener(
  function(request, sender, sendResponse) {
    if (request.text && (request.text == "getDOM")) {
      sendResponse({ dom: document.body.innerHTML });
    }
  }
);

popup.html

chrome.tabs.getSelected(null, function(tab) {
  chrome.tabs.sendMessage(tab.id, { action: "getDOM" }, function(response) {
    console.log(response);
  });
});

当我运行它时,我仍然得到相同的错误:

undefined
Port: Could not establish connection. Receiving end does not exist. lastError:30
undefined
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-11-04 06:10:31

“背景页面”、“弹出窗口”、“内容脚本”这几个术语仍然让您感到困惑;我强烈建议您更深入地研究一下。

关于你的问题,如果内容脚本或背景页面是可行的:

内容脚本:绝对

内容脚本是唯一可以访问网页DOM的扩展组件。

背景页/弹出窗口:可能(可能是最大。两者中的1个)

您可能需要让内容脚本将DOM内容传递给后台页面或弹出窗口进行进一步处理。

让我再说一遍,我强烈建议您更仔细地研究可用的文档!

也就是说,下面是一个示例扩展,它检索StackOverflow页面上的DOM内容并将其发送到后台页面,然后后台页面在控制台中打印该内容:

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"]
}
票数 205
EN

Stack Overflow用户

发布于 2016-12-01 17:13:02

您不必使用消息传递来获取或修改DOM。我改用了chrome.tabs.executeScript。在我的示例中,我仅使用activeTab权限,因此该脚本仅在活动选项卡上执行。

manifest.json的部分

"browser_action": {
    "default_title": "Test",
    "default_popup": "index.html"
},
"permissions": [
    "activeTab",
    "<all_urls>"
]

index.html

<!DOCTYPE html>
<html>
  <head></head>
  <body>
    <button id="test">TEST!</button>
    <script src="test.js"></script>
  </body>
</html>

test.js

document.getElementById("test").addEventListener('click', () => {
    console.log("Popup DOM fully loaded and parsed");

    function modifyDOM() {
        //You can play with your DOM here or check URL against your regex
        console.log('Tab script:');
        console.log(document.body);
        return document.body.innerHTML;
    }

    //We have permission to access the activeTab, so we can call chrome.tabs.executeScript:
    chrome.tabs.executeScript({
        code: '(' + modifyDOM + ')();' //argument here is a string but function.toString() returns function's code
    }, (results) => {
        //Here we have just the innerHTML and not DOM structure
        console.log('Popup script:')
        console.log(results[0]);
    });
});
票数 93
EN

Stack Overflow用户

发布于 2019-04-07 09:34:39

对于那些尝试gkalpak答案但不起作用的人,

请注意,只有当您的扩展在chrome启动期间启用时,chrome才会将内容脚本添加到所需的页面,并且在进行这些更改后重新启动浏览器也是一个好主意

票数 14
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19758028

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档