2017-10-18 228 views
1

我正在嘗試獲取輸入值並將其設置爲var以更改網頁值。我不知道這是否是正確的方式,但據我所知:/我需要使自動填充從我的擴展輸入中填充頁面。我試圖直接搜索我的input.value時做到這一點,但它總是顯示爲null,並且我也嘗試將輸入保存在localStorage中......但它不工作:(當我嘗試執行操作時,我會發布所有內容當我救我輸入的localStorage 很抱歉,如果這是一個愚蠢的問題,但我只是不能得到它的工作:(Chrome擴展 - 無法獲得輸入值

清單文件:

{ 
"manifest_version" : 2, 
"name": "sAVING iNPUT", 
"version": "1.0", 
"description" : "Click something pls", 
"version" : "1.0", 
"permissions" : ["<all_urls>"], 

"browser_action" : { 
    "default_popup" : "popup.html" 

} 
} 

Popup.html文件:

<!DOCTYPE html> 
<html> 
<head><title> activity</title></head> 
<body> 
<div> 
    <div> 
     E-Pasts 
     <input type="text" name="epasts" id="epasts"></input> 
    </div> 
    <button id="ielogoties" aonClick="saveInput()" > login </button> 
</div> 
    <script src="popup.js"> 
    function saveInput(){ 
     localStorage.setItem("epastss", document.getElementById("epasts")); 
    } 
    </script> 
</body> 
</html> 

Popup.js文件:

function injectTheScript() { 
chrome.tabs.query({active : true, currentWindow:true},function(tabs){ 
    chrome.tabs.executeScript(tabs[0].id,{file: "content_script.js"}); 
}); 

} 
document.getElementById("ielogoties").addEventListener 
("click",injectTheScript); 

content_script.js文件:

var drepasts = document.getElementById("email"); 
var epasts = localStorage.getItem("epastss") 


drepasts.value= epasts; 
alert("hehejr"); 
localStorage.removeItem("epasts"); 

現在,當我按下按鈕,我收到此錯誤:

拒絕,因爲它違反了以下內容安全策略指令執行內聯事件處理程序:「 script-src'self'blob:filesystem:chrome-extension-resource:「。 「內聯不安全」關鍵字,散列('sha256 -...')或一個隨機數('nonce -...')是啓用內聯執行所必需的。

回答

0

您需要聲明清單文件中的storage權限才能訪問localStorage

permissions部分應該是這樣的:

"permissions" : ["<all_urls>", "storage"], 

或者:

"permissions": [ 
    "<all_urls>", 
    "storage" 
], 

更多信息,請參見chrome.storage documentation


而且,我猜這只是您的文章錯字,但aonClick應該是onclick

<button id="ielogoties" aonClick="saveInput()" > login </button> 

的方式你的代碼是正確的,現在,它抓住了<input>元素本身並將其保存在localStorage中,然後檢索該值並嘗試將其插入ID爲「email」的元素中。這可能是你爲什麼得到null

要獲得輸入值,而不是輸入元素,你setItem聲明改成這樣:

localStorage.setItem("epastss", document.getElementById("epasts").value); 
+1

它由我一個愚蠢的錯誤,但它仍然顯示爲空:( – TheProfesor

+0

@TheProfesor你是不是想保存輸入元素或其值?如果要保存它的值,則需要將'setItem'值更改爲'document.getElementById(「epasts」).value'。 – freginold