Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing all the window variables of the current tab in chrome extension [duplicate]

Can anyone post the code for accessing the window variables in chrome extension. I need to access the window variables when i click the chrome extension button. I am getting the window object, but not with all the variables loaded. I know we can create it by injecting the script. But i am not getting how to achieve it. Currently I am trying the following code to get the page source of the current active tab.

 chrome.tabs.executeScript({code:
            "document.getElementsByTagName('html')[0].innerHTML"
        }, function(result) {
    var value = result[0];
    console.log(value);
    chrome.tabs.query({currentWindow: true, active: true}, function(tabs) {
        callback({
            url: tabs[0].url,
            title: tabs[0].title,
            jsonValue: value
        });
    });
}); 

Please help me in solving this issue. It would be highly appreciated.

like image 431
Srinivas B Avatar asked Sep 18 '15 06:09

Srinivas B


Video Answer


1 Answers

What you are asking for is to inject a script an get the value of a variable defined in the original page script. There are two answers to this problem:

1. Official Google answer

This is not possible. Content script injected in a page is sandboxed and can't access to original page javascript scope. This means that you can't access to variable, function and objects defined in the original page's javascript. And your variable, function and objects will not be accessible from the original page.

Only the DOM of the page is shared. That allow you to modify the content of the page. But you can't, for example, delete an existing event handler.

This is for evident security and safety reason. If you override without knowing it a function of the original page, it would break it.

Take a look here for more information

2. Unofficial and dirty answer

There is a way to bypass the chrome sand box restriction. This come with the shared DOM that allow you to add a <script src="..."><\script> to the page. The script will be loaded and executed in the original page's javascript VM so you will have access to the global javascript scope.

But this way, will not have access to the Chrome extension API, because you are running code in the original page. So the communication with the background page or the injected Content Script will be difficult.

A common way to do this is to add a hidden <div> to the page and put in it the result you want to send to your Content Script. You put the result as text (with JSON.stringify for example) and then read the result with your Content Script.

It's really dirty and it have to be use only in last try.

like image 98
Emrys Myrooin Avatar answered Oct 17 '22 00:10

Emrys Myrooin