Chrome Extension - access document/page variable from extension

后端 未结 2 1898
执笔经年
执笔经年 2021-02-13 12:19

I\'m trying to develop extension that works only on specified pages - If page owner adds global variable into their code (for eg. ACCEPT_STATS = true;) I want to ex

2条回答
  •  野的像风
    2021-02-13 13:05

    The javascript running on the page is running in a different "isolated world" than the javascript that you inject using content scripts. Google Chrome keeps these two worlds separate for security reasons and therefore you can't just read window.XYZ on any window. More info on how isolated worlds work : http://www.youtube.com/watch?v=laLudeUmXHM

    The correct way of implementing this is by communicating with the page is via window.postMessage API. Here're how I would go about it :

    1. Inject a content script into each tab
    2. Send a message to the tab via window.postMessage
    3. If the page understands this message, it responds correctly (again via window.postMessage)
    4. Content script executes the code that it needed to execute.

    HTH

提交回复
热议问题