javascript Chrome 扩展 - 获取 DOM 内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19758028/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 16:41:51  来源:igfitidea点击:

Chrome Extension - Get DOM content

javascriptgoogle-chrome-extension

提问by brandonhilkert

I'm trying to access the activeTab DOM content from my popup. Here is my manifest:

我正在尝试从弹出窗口访问 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"
  }
}

I'm really confused whether background scripts (event pages with persistence: false) or content_scripts are the way to go. I've read all the documentation and other SO posts and it still makes no sense to me.

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

Can someone explain why I might use one over the other.

有人可以解释为什么我可能会使用一个而不是另一个。

Here is the background.js that I've been trying:

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

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

And I'm just executing this from the popup console:

我只是从弹出式控制台执行此操作:

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

I'm getting:

我越来越:

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

UPDATE:

更新:

{
  "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

内容.js

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

popup.html

弹出窗口.html

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

When I run it, I still get the same error:

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

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

回答by gkalpak

The terms "background page", "popup", "content script" are still confusing you; I strongly suggest a more in-depth look at the Google Chrome Extensions Documentation.

术语“背景页面”、“弹出窗口”、“内容脚本”仍然让您感到困惑;我强烈建议更深入地查看Google Chrome 扩展文档

Regarding your question if content scripts or background pages are the way to go:

关于您的问题,内容脚本或背景页面是否可行:

Content scripts: Definitely
Content scripts are the only component of an extension that has access to the web-page's DOM.

内容脚本:当然,
内容脚本是扩展程序中唯一可以访问网页 DOM 的组件。

Background page / Popup: Maybe (probably max. 1 of the two)
You may need to have the content script pass the DOM content to either a background page or the popup for further processing.

后台页面/弹出窗口:可能(最多可能是两者中的 1 个)
您可能需要让内容脚本将 DOM 内容传递给后台页面或弹出窗口以进行进一步处理。



Let me repeat that I strongly recommend a more careful study of the available documentation!
That said, here is a sample extension that retrieves the DOM content on StackOverflow pages and sends it to the background page, which in turn prints it in the console:

让我重复一遍,我强烈建议对可用文档进行更仔细的研究!
也就是说,这是一个示例扩展,它检索 StackOverflow 页面上的 DOM 内容并将其发送到后台页面,后台页面又将其打印在控制台中:

background.js:

背景.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:

内容.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:

清单.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"]
}

回答by Oskar

You don't have to use the message passing to obtain or modify DOM. I used chrome.tabs.executeScriptinstead. In my example I am using only activeTab permission, therefore the script is executed only on the active tab.

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

part of manifest.json

manifest.json 的一部分

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

index.html

索引.html

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

test.js

测试.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]);
    });
});

回答by bxN5

For those who tried gkalpak answer and it did not work,

对于那些尝试过 gkalpak 回答但没有用的人,

be aware that chrome will add the content script to a needed page only when your extension enabled during chrome launch and also a good idea restart browser after making these changes

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