Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome Packaged App - Message passing from background.js to another script page

I'm making a Chrome Packaged app using AngularJS and I'm simply attempting to send a message from my background script ("runtime.js") to another javascript file in my project.

Manifest.json

  {
      "name": "App Name",
      "description": "Chrome Packaged",
      "version": "0.0.9",
      "manifest_version": 2,
      "icons": {
        "16": "img/icon16.png",
        "48": "img/icon48.png",
        "128":"img/icon128.png"
      },
      "app": {
        "background": {
          "scripts": ["runtime.js"]
        }
      },
      "permissions": [
        "alarms",
        "storage",
        "unlimitedStorage",
        "notifications",
        "app.runtime"
      ]
    }

runtime.js

chrome.app.runtime.onLaunched.addListener(function() {
    chrome.app.window.create('index.html', {
    minWidth: 400,
    minHeight: 700,
    bounds: {
        width: 1000,
        height: 700
    }
    });    
});

chrome.runtime.sendMessage({message: "hello"}, function() {
    console.log('sent')
});

main.js

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    console.log('message received!');
});

The error I keep getting when I inspect the background page is "Port: Could not establish connection. Receiving end does not exist."

Any ideas for what might be the problem? Thanks!

like image 308
adam8810 Avatar asked Mar 21 '23 15:03

adam8810


1 Answers

You probably just need to wait for index.html (which I assume is pulling in main.js) to load before you send the message. However, you can actually make a direct function call through the window object you get back from chrome.app.window.create instead of sending a message.

chrome.app.runtime.onLaunched.addListener(function() {
    chrome.app.window.create('index.html', {
        minWidth: 400,
        minHeight: 700,
        bounds: {
            width: 1000,
            height: 700
        }
    }, function (myWindow) {
        myWindow.contentWindow.addEventListener('load', function(e) {
            myWindow.contentWindow.functionFromMainJs('hello');
        });
    });    
});
like image 172
courage Avatar answered Apr 06 '23 01:04

courage