Chrome扩展程序-获取DOM内容

我正在尝试从弹出窗口中访问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.innertHTML });

    }

  }

);

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


慕侠2389804
浏览 2042回答 3
3回答

开心每一天1111

对于那些尝试gkalpak答案但没有效果的人,请注意,只有在chrome启动过程中启用了扩展程序后,chrome才会将内容脚本添加到所需的页面,并且最好在进行这些更改后重新启动浏览器
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript