سؤال

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