0

Suppose I have a jsp page that holds session data like this,

<input type="hidden" id="sessionData" value="${login}"/>

Now, I have a chrome extension and inside the js file (e.g., "popup.js") I want to access the data using getElementById. For example,

chrome.tabs.getSelected(null,function(tab) {
    //alert(tab.id);
    var sessionData = document.getElementById('sessionData').value;
    console.log('session data is '+sessionData);
    alert(sessionData.lang);
});

Unfortunately, I can't fetch any session data. No alert is showing. Before fetching session data, alert(tab.id); shows the tab id correctly. (Please don't suggest that chrome.tabs.getSelected is deprecated; I already know that.)

Teepeemm
  • 4,331
  • 5
  • 35
  • 58
Ataur Rahman Munna
  • 3,887
  • 1
  • 23
  • 34
  • Just to make sure it's said. That is a **horrible, horrible** way of keeping a session. There's absolutely **nothing** stopping the user from changing their dom so that ``. – Madara's Ghost Nov 29 '15 at 09:44
  • this is not for production env, rather for during developing purpose. @MadaraUchiha – Ataur Rahman Munna Nov 29 '15 at 10:01
  • An example with code: [How to store the values retrieved from content script into textboxes with a button click](http://stackoverflow.com/a/32166124) For more examples simply google `stackoverflow chrome extension access web page from popup`. Make sure to read the [extension architecture overview](https://developer.chrome.com/extensions/overview#arch) – wOxxOm Nov 29 '15 at 13:14
  • BTW, the deprecated api tells you how to do it without the deprecation: `chrome.tabs.query({active:true},function(tab){});`. – Teepeemm Nov 29 '15 at 19:38

1 Answers1

2

Use chrome.tabs.executeScript() to execute code in a tab like this:

chrome.tabs.executeScript(null, {file: "content_script.js"});

content_script.js:

var sessionData = document.getElementById('sessionData').value;
console.log('session data is '+sessionData);
alert(sessionData.lang);

NOTE : You need activeTab permissions to execute code in an active tab

"permissions": [
  "activeTab"
]
Siddharth
  • 6,966
  • 2
  • 19
  • 34