繁体   English   中英

Chrome扩展程序获取DOM文本,并在单击按钮时将其显示在popup.html中

[英]Chrome extension get DOM text and show it in popup.html on click on button

关于SO和其他方面的信息很多,但我无法使它起作用!

我有这个popup.html:

<html>
  <head>
    <title>My popup that should display the DOM</title>
    <script src="popup.js"></script>
  </head>
  <body>
        <button id="btn">Click!</button>
        <input type="text" id="info"> 
  </body>
</html>

我的manifest.json:

{
"manifest_version": 2,
"name":    "Get HTML example w/ popup",
"version": "0.0",

"background": {
    "persistent": false,
    "scripts": ["background.js"]
},
"content_scripts": [{
    "matches": [ "http://*/*", "https://*/*" ],
    "js":      ["jquery-2.2.1.min.js","content.js"]
}],
"browser_action": {
    "default_icon": "icon.png",
    "default_title": "Get HTML example",
    "default_popup": "popup.html"
},
"permissions": ["tabs"]
}

background.js:

function doStuffWithDOM(infoHtmlText) {
    alert("I received the following DOM content:\n" + infoHtmlText);
    chrome.extension.getBackgroundPage().info = infoHtmlText;
}


chrome.tabs.onUpdated.addListener(function(id,changeInfo,tab){
        if(changeInfo.status=='complete'){ //To send message after the webpage has loaded
            chrome.tabs.sendMessage(tab.id, { status: "ok" },function(response){
              infoHtmlText = $("#domElement").text();
               doStuffWithDOM(infoHtmlText);
            });
          }
})

content.js:

chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
    /* If the received message has the expected format... */
    if (msg.status && (msg.status == "ok")) {
        /* Call the specified callback, passing
           the web-pages DOM content as argument */
        sendResponse("something?");
    }
});

有一个简单的示例,您可以在弹出窗口中单击一个按钮,然后从DOM中获取内容并将其显示在弹出窗口中?

这是基于您的代码的示例代码:

popup.js

function hello() {
   var  name = document.getElementById('info').value;
   alert("Hello " +name);
}

document.getElementById('btn').addEventListener('click', hello);

popup.html

<html>
  <head>
    <title>My popup that should display the DOM</title>

  </head>
  <body>
        <button id="btn">Click!</button>
        <input type="text" id="info"> 
        <script type="text/javascript" src="popup.js"></script>
  </body>
</html>

manifest.json

{
"manifest_version": 2,
"name":    "Get HTML example w/ popup",
"version": "0.0",
"background": {
    "persistent": false,
    "scripts": ["background.js"]
},
"browser_action": {
    "default_icon": "icon.png",
    "default_title": "Get HTML example",
    "default_popup": "popup.html"
},
"permissions": ["tabs", "<all_urls>"]
}

background.js :留为空白(不确定,因为我是chrome开发的新手),但它正在运行。

我从这个SO问题得到了答案,如果您直接使用内联标头,则会遇到此错误消息:

拒绝执行内联事件处理程序,因为它违反了以下内容安全策略指令:“ script-src'self'chrome-extension-resource:”。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM