使用Chrome扩展程序访问页面对象 [英] Accessing a pages object using a Chrome Extension

查看:291
本文介绍了使用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扩展程序访问页面对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆