开发者

How do i get the local storage value in background page?

开发者 https://www.devze.com 2023-03-24 23:02 出处:网络
I am newbie as far as developing chrome extension is concerned. I am testing an extension. In this i have a background page and options page. In options page i am storing user entered password in loc

I am newbie as far as developing chrome extension is concerned.

I am testing an extension. In this i have a background page and options page. In options page i am storing user entered password in local storage which i want to retrieve in the background page that is on click of browser icon.

My options page is :

<html>
<head>
<title>Options for Password</title>
<script>
 function savePassword()
  {
 window.localStorage.setItem('password', txtPassword.value);


  }
</script>   
</head>
<body >
<h1>Enter Password</h1>
<input type='password' name='txtPassword' id='txtPassword'/>
<br />
<button onclick='savePassword();'>Save</button>
<br />
</body>
</html>

And my background page is:

<html>
<head>
<script>
 // Called when the user clicks on the browser action.
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(null, {code:"alert('password from tab:'+window.localStorage.getItem('password'开发者_开发技巧));getfeedback_dialog_submitButton.setAttribute('onclick', 'if(gettext.value==\'"+window.localStorage.getItem(password)'+"\'){document.body.removeChild(getfeedbackcontainer);document.body.removeChild(getfeedbackoverlay);}');"});
});


</script>
</head>
</html>

When i save password through options page and then i click on browser action then i am getting the alert password from tab:null.

I am confused how to retrieve the value stored in the local storage?


Your code gets the localStorage value from the page where the browser action is clicked, where it is null. Change your quotes to get it at the background page:

chrome.tabs.executeScript(null, {code:"alert('password from tab:"+window.localStorage.getItem('password')+"');"});

Note that this may allow for code injection.

EDIT: Do this, it should work as long as your variables are defined properly and window.localStorage.getItem('password') is expected to be a string:

chrome.tabs.executeScript(null, {code:"alert('password from tab:"+window.localStorage.getItem('password')+"');"
+"getfeedback_dialog_submitButton.addEventListener('click', function(event){if(gettext.value=='"+window.localStorage.getItem('password')+"')"
+"{document.body.removeChild(getfeedbackcontainer);document.body.removeChild(getfeedbackoverlay);}},false);"});

I split your code into multiple lines for readability.

0

精彩评论

暂无评论...
验证码 换一张
取 消