문제

What's the preferred way to get the eventPage from a content script? The old method (chrome.extension.getBackgroundPage) has been replaced with chrome.runtime.getBackgroundPage, but the chrome.runtime API is not accessible from content scripts.

도움이 되었습니까?

해결책

The chrome.extension.getBackgroundPage method is to access the background page from a browser action page. To access the background/event-page js, the below code should work from a content script:

 chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
   console.log(response.farewell);
 });

In the background-page/event page JS you have to setup a listener to listen for requests from content scripts:

chrome.runtime.onMessage.addListener(
 function(request, sender, sendResponse) {
    console.log(sender.tab ?
            "from a content script:" + sender.tab.url :
            "from the extension");
    if (request.greeting == "hello")
        sendResponse({farewell: "goodbye"});
});

Hope this helps. chrome.runtime.getBackgroundPage from content script will never work; you can only send messages to it(like above).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top