【问题标题】:Accessing Current Tab DOM Object from a Chrome Extension从 Chrome 扩展程序访问当前选项卡 DOM 对象
【发布时间】:2016-12-28 19:08:36
【问题描述】:

我一直在寻找如何做到这一点。我发现了一些最值得注意的文章

Accessing Current Tab DOM Object from "popup.html"?

但是,我对 JavaScript 和制作 chrome 扩展非常陌生,但我遇到了死胡同。 我的猜测是没有收到回复,这解释了为什么document.write("Hellp") 不工作。任何解决此问题的帮助将不胜感激。

我有三个主要文件

manifest.json

{
 "name": "My First Extension",
 "version": "1.0",
 "description": "The first extension that I made.",
 "browser_action": 
 {
  "default_icon": "icon.png",
  "popup": "popup.html"
 },
 "permissions":
 [
  "tabs"
 ],
 "content_scripts": 
 [{
  "matches": ["<all_urls>"],
  "js": ["dom.js"]
 }]
}

popup.html

<html>     
 <body>     
 </body>    
 <script>

 chrome.tabs.getSelected(null, function(tab)
 {
  // Send a request to the content script.
  chrome.tabs.sendRequest(tab.id, {action: "getDOM"}, function(response)
  {
   document.write("Hello");
   document.write(response.title)
  });
 });

 </script>
</html>

dom.js

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) 
{
 if (request.action == "getDOM")
  sendResponse({dom: document.getElementsByTagName("body")[0]});
 else
  sendResponse({}); // Send nothing..
});

【问题讨论】:

    标签: javascript


    【解决方案1】:

    我看到这是一个较老的问题,但没有答案,我遇到了同样的问题。也许这是一项安全功能,但您似乎无法返回 DOM 对象。但是,您可以返回文本。所以对于 dom.js:

    chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
     if (request.action == "getDOM")
       sendResponse({dom: document.body.innerHTML});
     else
       sendResponse({}); // Send nothing..
    });
    

    【讨论】:

    • 其实DOM对象是无法发送的,因为它们是not JSON-serializable
    • 那么我们如何才能将 DOM 元素放到弹出窗口中呢? @GaurangTandon
    • @Despertaweb 我已经写了一年了,老实说我已经忘记了我项目的那一部分。好吧,我想我已经通过使用背景页面或发送 innerHTML 并使用某种全局标志来协调黑白内容脚本和背景页面来进行管理。抱歉,信息太少了!
    • @GaurangTandon 不是问题。 “几个”小时后我自己解决了!无论如何谢谢:D
    • @Despertaweb 现在我有兴趣了解解决方案。 :P 你介意把它作为答案发布吗?
    【解决方案2】:

    我正在开发一个扩展,它将元素的 html 作为文本传输,然后使用 innerHTML 重新构建元素。 希望阐明如何从当前页面获取 DOM 元素**

    这就是我获得 DOM 的方式:

    Manifest.json

    {
        "manifest_version": 2,
        "version" : "2.0",
        "name": "Prettify search",
        "description": "This extension shows a search result from the current page",
      "icons":{
        "128": "./img/icon128.png",
        "48": "./img/icon48.png",
        "16": "./img/icon16.png"
      },
     "page_action": {
        "default_icon": "./img/icon16.png",
        "default_popup": "popup.html",
        "default_title": "Prettify Results!"
      },
    
    // If the context is the Mach url = sends a message to eventPage.js: active icon
      "content_scripts": [
        {
          "matches": ["http://www.whatever.cat/*"],
          "js": ["./js/content.js", "./js/jquery-3.1.1.min.js"]
        }
      ],
    
      "permissions": [
        "tabs",
        "http://www.whatever.cat/*",
        "http://loripsum.net/*"  //If you need to call and API here it goes
      ],
    
      "background":{
        "scripts": ["./js/eventPage.js"],
        "persistent": false
      }
    
    }
    

    Popup.js

        $(function() {
            chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    
                chrome.tabs.sendMessage(tabs[0].id, {action: "getPage"}, function(response) {
    
                    var importedCode = response.searchResults;
                    var fakeHtml = document.createElement( 'html' );
                    fakeHtml.innerHTML = importedCode; // recieved String becomes html
    
    
              });
            });
    

    Eventpage.js

    >Able/disable the extension button 
    chrome.runtime.onMessage.addListener(function(req, sender, resp) {
        if(req.todo === 'showPageAction'){
    
            chrome.tabs.query({active:true, currentWindow:true}, function(tabs) {
                chrome.pageAction.show(tabs[0].id);
            });
        }
    });
    

    content.js

    Content_Scripts 不能使用 Chrome API 来启用或禁用 >extension 图标。我们传消息给Event_Page,js,他确实可以 使用 API

    chrome.runtime.sendMessage({ todo: "showPageAction"});
    window.onload = function() {
    
    chrome.runtime.onMessage.addListener(
      function(request, sender, sendResponse) {
        console.log(sender.tab ?
                    "from a content script:" + sender.tab.url :
                    "from the extension");
        if (request.action == "getPage"){
            sendResponse({searchResults: document.body.innerHTML});
          }
      });  
    };
    

    popup.html

    只需链接 popup.js

    【讨论】:

    • 可能有助于总结一下,您将元素的 html 作为文本传输,然后使用 innerHTML 重新构建元素。
    猜你喜欢
    • 1970-01-01
    • 2016-09-13
    • 2016-11-30
    • 2012-04-21
    • 1970-01-01
    • 2012-04-27
    • 1970-01-01
    • 2017-04-30
    • 1970-01-01
    相关资源
    最近更新 更多