2017-02-10 69 views
0

我正在做一個Chrome擴展,當按下按鈕時,我得到當前的URL和輸入字段中的值。嘗試訪問鉻擴展中的表單元素的值時出錯

,但我得到的錯誤:

Uncaught TypeError: Cannot read property 'value' of null at HTMLButtonElement.myAlert 

在該行:

var ip = document.getElementById('ip_dns').value; 

如何獲取並存儲該值的正確方法是什麼?

這裏是我的代碼:

popup.html

<!doctype html> 
<html> 
    <head> 
    <title>DNS Teste</title> 
    <script src="popup.js"></script> 
    </head> 
    <body> 
    <form> 
     IP DNS 
     <input type="text" ip="ip_dns"> 
     <button id="btn">Teste</button> 
    </form> 
    </body> 
</html> 

popup.js

function myAlert(){ 
    chrome.tabs.getSelected(null, function(tab) { 
    var url = tab.url; 
    console.log("url: "+ url); 
    }); 
    var ip = document.getElementById('ip_dns').value; 
    console.log("IP: "+ip); 
} 

document.addEventListener('DOMContentLoaded', function() { 
    document.getElementById('btn').addEventListener('click', myAlert); 
}); 

的manifest.json

{ 
    "manifest_version": 2, 

    "name": "Getting started example", 
    "description": "This extension shows a Google Image search result for the current page", 
    "version": "1.0", 

    "browser_action": { 
    "default_icon": "icon.png", 
    "default_popup": "popup.html" 
    }, 
    "permissions": [ 
    "activeTab", 
    "https://ajax.googleapis.com/", 
    "tabs" 
    ] 
} 
+0

你在這裏錯字:,也許這就是問題?將其更改爲

回答

0

它的工作原理

function myAlert(){ 
 
    // chrome.tabs.getSelected(null, function(tab) { 
 
    // var url = tab.url; 
 
    // console.log("url: "+ url); 
 
    // }); 
 
    var ip = document.getElementById('ip_dns').value; 
 
    console.log("IP: "+ip); 
 
} 
 

 
document.addEventListener('DOMContentLoaded', function() { 
 
    document.getElementById('btn').addEventListener('click', myAlert); 
 
});
<form> 
 
    IP DNS 
 
    <input type="text" id="ip_dns"> 
 
    <button id="btn">Teste</button> 
 
</form>