Yasser
Yasser

Reputation: 406

Messaging directly from web page in Safari like Chrome

Is there any way to post messages directly from web pages to global page like Chrome's

chrome.runtime.sendMessage, chrome.runtime.onMessageExternal

API functions in Safari?

I've used AngularJS in my web app, and can't think of any clean way integrating it with injected scripts to pass messages to background. My web app is going to initiate some commands to background and get results basically. Currently, trying to convert my Chrome extension to Safari.

Or is there any way my Angular controller speak with injected script if above approach is not possible so that Angular be responsible for updating DOM not injected script?

Upvotes: 1

Views: 1903

Answers (1)

Pawel Uchida-Psztyc
Pawel Uchida-Psztyc

Reputation: 3838

Content scripts injected into page are isolated from page's javascript. However they share DOM. Event if you can't call javascript function from content script directly you can use window.postMessage to send some message to content script and listen for message inside CS:

(according to extensions documentation): contentscript.js

window.addEventListener("message", function(event) {
  // We only accept messages from ourselves
  if (event.source != window)
    return;
  var passedDataObject = event.data;
  //...
  }
}, false);

And on the web page:

window.postMessage({ /* Object to pass */ }, "*");

This is regular message passing on the web sites. postMessage takes two arguments: 1st is a data to pass and second is a target origin (see https://developer.mozilla.org/en-US/docs/Web/API/Window.postMessage for explanations).

Onmessage event have "source" attribute which tells you from which window/frame message come from. In your case you want to listen only for events from page where CS was injected to: if (event.source != window) return;

Edited: Documentation for content scripts and message passing you'll find at https://developer.chrome.com/extensions/content_scripts

Upvotes: 3

Related Questions