我只需要从Chrome扩展程序访问运行内容脚本的页面上的变量。
I simply have to access an object that is a variable on the page that I am running my content script on from my Chrome Extension.
我了解环境以及运行内容脚本和注入脚本的孤立世界,并且有可能使用注入脚本获取一些变量,然后将它们发送回去。
I know about the environments and their isolated worlds in which the content scripts and injected scripts run and that it's possible to get some variables using the injected scripts and then send them back.
我一直在寻找有关此问题的其他答案以及大多数针对其他类型变量的工作,这是执行此问题的基本方法,但目前尚无访问对象的方法。
I have searched for other answers regarding this question and most work for other type of variables and are the basic way of doing it but none currently work for accessing objects.
任何当前的解决方案或解决方法?
Any current solutions or workarounds?
编辑:我使用的解决方案:
内容脚本:
//Sends an object from the page to the background page as a string window.addEventListener("message", function(message) { if (message.data.from == "myCS") { chrome.runtime.sendMessage({ siteObject: message.data.prop }); } }); var myScript = document.createElement("script"); myScript.innerHTML = 'window.postMessage({from: "myCS", prop: JSON.stringify(OBJECT)},"*");'; document.body.appendChild(myScript);Background.js:
Background.js:
//Info receiver chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) { //When the content script sends the sites object to extract the needed data if (message.siteObject !== undefined) { console.log(message.siteObject); //Process the data } });推荐答案
您可以尝试注入 script 标记以访问对象。如果需要,您可以使用消息传递与您的扩展进行通信。例如,假设您要在页面中访问的对象称为 pageObject :
You can try to inject a script tag in the page to access the object. If needed, you could use messaging to communicate with your extension. For example, assuming the object you want to access in your page is called pageObject:
content1。 js
//this code will add a new property to the page's object var myOwnData = "createdFromContentScript"; var myScript = document.createElement("script"); myScript.innerHTML = "pageObject.myOwnData = " + myOwnData; document.body.appendChild(myScript);content2.js
//this code will read a property from the existing object and send it to background page window.addEventListener("message", function(message) { if (message.data.from == "myCS") { chrome.runtime.sendMessage({theProperty: message.data.prop}); } }); var myScript = document.createElement("script"); myScript.innerHTML = 'window.postMessage({from: "myCS", prop: pageObject.existingProperty},"*");'; document.body.appendChild(myScript);更多推荐
使用Chrome扩展程序访问页面对象
发布评论