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

↘锁芯ラ 提交于 2021-02-07 12:17:19

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/32644906/accessing-all-the-window-variables-of-the-current-tab-in-chrome-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!