2012-11-13 73 views
3

我想知道,如果我有一個Chrome擴展,當你點擊圖標時彈出了一個彈出窗口,並且該彈出窗口有一個文本框可以輸入數據,javascript看起來會是什麼樣子文本框內的文本?從Chrome擴展彈出窗口獲得價值

更新:我知道如何從文本框中獲取值,但我的問題是,如何特別訪問我的popup.html文件的元素?我嘗試訪問document.getElementById等,但它獲取實際頁面內容中的元素,而不是我自定義的彈出窗口。

+0

聽起來像一個哲學問題... :) – gdoron

+0

哈哈也許是這樣。誰知道。我只是想知道,在我的popout.js文件中,如果該文本框的ID爲「input」,代碼將訪問彈出窗口中的元素。 – barndog

+0

如果您正在尋找提示用戶直接輸入的最簡單方法,您是否考慮過'提示符'? –

回答

5

我們可以通過綁定的事件偵聽器如以下方式點擊按鈕事件的一些事件得到彈出頁面的文本框中的值:

假設manifest.json文件中是這樣的:

{ 
    "manifest_version": 2, 

    "name": "Wonderful extension", 
    "description": "Wonderful extension - gets value from textbox", 
    "version": "1.0", 

    "browser_action": { 
    "default_icon": "images/icon.png", 
    "default_popup": "popup.html" 
    } 
} 

和popup.html是這樣的:

<!DOCTYPE html> 
<html> 
    <head> 
    <title>Wonderful Extension</title> 
    <script src="popup.js"></script>  
    </head> 
    <body> 

    <div style="padding: 20px 20px 20px 20px;">   
     <h3>Hello,</h3> 
     <p>Please enter your name : </p>   
     <input id="name_textbox" />     
     <button id="ok_btn" type="button">OK</button> 
    </div>  

    </body> 
</html> 

那麼我們就可以綁定在文檔中的事件以下列方式從文本框中獲取值:

文件popup.js:

document.addEventListener('DOMContentLoaded', documentEvents , false); 

function myAction(input) { 
    console.log("input value is : " + input.value); 
    alert("The entered data is : " + input.value); 
    // do processing with data 
    // you need to right click the extension icon and choose "inspect popup" 
    // to view the messages appearing on the console. 
} 

function documentEvents() {  
    document.getElementById('ok_btn').addEventListener('click', 
    function() { myAction(document.getElementById('name_textbox')); 
    }); 

    // you can add listeners for other objects (like other buttons) here 
} 

進入彈出頁面的其他元素,我們可以使用類似的方法。

相關問題