eternal
eternal

Reputation: 419

Message from devtools panel to contents script when devtools opened in separate window

I am writing a Chrome extension and I need send message from devtools panel which I created to content script. I've already done this:

devtools.js

$(function () {
    inputField.trigger('focus')
    chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
        chrome.tabs.sendMessage(tabs[0].id, {content: 'content'})
        chrome.runtime.onMessage.addListener(function (message) {
            if (!jQuery.isEmptyObject(message.pageHTML)) {
                pageHTML = message.pageHTML
            }
        })
    })

})

content.js

chrome.runtime.sendMessage(extensionID, {pageHTML: $('html').html()});

But it works only when devtools is pinned to any tab side, to the right, for example. When I open devtools as separate window, script loses its connection with content script and I have error:

Error handling response: TypeError: Cannot read property 'id' of undefined

So how do I fix this?

Upvotes: 2

Views: 414

Answers (1)

Under_Koen
Under_Koen

Reputation: 1078

You can get the id of the inspected window with chrome.devtools.inspectedWindow.tabId.

devtools.js

$(function () {
    inputField.trigger('focus')
    chrome.tabs.sendMessage(chrome.devtools.inspectedWindow.tabId, {content: 'content'})
    chrome.runtime.onMessage.addListener(function (message) {
        if (!jQuery.isEmptyObject(message.pageHTML)) {
            pageHTML = message.pageHTML
        }
    })
})

The sendMessage accepts a response handler, with this you could maybe remove the listener which you register just after sending the message. more info

Upvotes: 1

Related Questions