使用Chrome扩展程序访问页面对象

编程入门 行业动态 更新时间:2024-10-27 07:29:04
本文介绍了使用Chrome扩展程序访问页面对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我只需要从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扩展程序访问页面对象

本文发布于:2023-05-31 22:04:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/400218.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   页面   程序   Chrome

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!