Need to get the user page ID.

GreasMonkey can access an object

alert(current.uid); 

However, from the assembled chrome extension, access to the object cannot be obtained, says, undefined.

Actually, the question. GM also gets access to the page objects. How can you implement it in your own home?

Code:

 var response = new XMLHttpRequest(); var url = '127.0.0.1/stat.php?uid='+current.uid; response.onload=function(){ showMSG(response.responseText); } } response.onerror=function(){ showMSG('Ошибка загрузки данных статистики'); return false; } response.open('GET',url,true); response.send(); } 
  • And show the code to the task? - UserName
  • @UserName attached - Vitali RS
  • From GreasMonkey it is possible to get access through a simple assignment. Interested in how you can access from the assembled extension. - Vitali RS
  • @UserName, thanks, now I will try, and I will say. what happened. - Vitali RS
  • @UserName, added your script to web_accessible_resources. In the end, all the same, swears, current is not defined - Vitaly RS

1 answer 1

Neither the content_scripts nor the background have access to the variables and functions defined on the web page, since they are executed in an isolated environment.

In order to run the code in the context of a web page, you need to manifest.json the key web_accessible_resources in manifest.json . This key indicates which scripts can be executed in the context of a web page.


Add the key to manifest.json :

"web_accessible_resources" : ["lib/inject/script.js"]

From the content_scripts embed the code on the page:

 var script = document.createElement('script'); script.src = chrome.extension.getURL("lib/inject/script.js"); document.head.appendChild(script); 

From script.js you can perform actions in the context of a web page:

 alert(current.oid); 

In order to get the result of the work you need to define the key externally_connectable in manifest.json . The values ​​of this key indicate which pages can communicate with the extension via runtime.connect and runtime.sendMessage .


Add the key to manifest.json :

 "externally_connectable": { "matches": ["*://*.example.com/*"] } 

Sending a message from the page:

 // Идентификатор расширения, с которым нужно связаться var extensionId = "abcdefghijklmnoabcdefhijklmnoabc"; chrome.runtime.sendMessage(extensionId, {oid: current.oid}); 

In the extension, you need to set a listener for the onMessageExternal event:

 chrome.runtime.onMessageExternal.addListener( function (request, sender, sendResponse) { if (request.oid) func(request.oid); }); 

This is not the only way. You can send data using DOM 's page or window.postMessage .


Web Accessible Resources | externally_connectable | Execution environment