How do I access the popup page DOM from bg page in Chrome extension?

前端 未结 3 2109
鱼传尺愫
鱼传尺愫 2021-02-08 14:14

In Google Chrome\'s extension developer section, it says

The HTML pages inside an extension have complete access to each other\'s DOMs, and they can invoke f

3条回答
  •  长情又很酷
    2021-02-08 14:47

    As other answers mention, you can call background.js functions from popup.js like so:

    var _background = chrome.extension.getBackgroundPage();
    _background.backgroundJsFunction();
    

    But to access popup.js or popup.html from background.js, you're supposed to use the messages architecture like so:

    // in background.js
    chrome.runtime.sendMessage( { property: value } );
    
    // in popup.js
    chrome.runtime.onMessage.addListener(handleBackgroundMessages);
    function handleBackgroundMessages(message)
    {
        if (message.property === value)
            // do stuff
    }
    

    However, it seems that you can synchronously access popup.js from background.js, just like you can synchronously access the other way around. chrome.extension.getViews can get you the popup window object, and you can use that to call functions, access variables, and access the DOM.

    var _popup = chrome.extension.getViews( { type: 'popup' } )[0];
    _popup.popupJsFunction();
    _popup.document.getElementById('element');
    _popup.document.title = 'poop'
    

    Note that getViews() will return [] if the popup is not open, so you have to handle that.

    I'm not sure why no one else mentioned this. Perhaps there's some pitfalls or bad practices to this that I've overlooked? But in my limited testing in my own extension, it seems to work.

提交回复
热议问题