2016-03-16 54 views
0

有很多關於SO和其他地方的信息,但是我無法使它工作!Chrome擴展程序獲取DOM文本並在popup.html上顯示它,點擊按鈕

我有這個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獲取內容並在彈出窗口中顯示它?

回答

2

這裏是你的代碼基於一個示例代碼:

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: LEA已經空白(不知道這是因爲我是鉻開發新手),但它工作。

我從這個SO question答案,如果你直接使用內聯頭,你會遇到這樣的錯誤消息:

拒絕,因爲它違反了以下內容安全策略指令執行內聯事件處理程序:「腳本 - src'self'chrome-extension-resource:「。

相關問題