The My Opera forums have been replaced with forums.opera.com. Please head over there to discuss Opera's products and features

See the new Forums

You need to be logged in to post in the forums. If you do not have an account, please sign up first.

Go to last post

26. November 2011, 13:35:31

stefanvd

Posts: 69

send back to source tab

I got a open page, when i click on the url. It inject something in the page.
But about a rondom time it send a message to the background page. and the background must send it back to tab id where it is sended. (also if the tab is not focused)

How create this?

current Background page:
opera.extension.onmessage = function(e) {
switch (e.data.action) {
case 'received':
e.source.postMessage({
action: 'thattab'
});
break;

}
}

Inject script got this:
if(window.top == window.self) {
opera.extension.onmessage = function(e) {
switch (e.data.action) {
// Update the entire settings object
case 'thattab':
settings = e.data.settings;
run(e);
break;
}
}
}
function run(e) {
...
if(...){
window.onload = function() {opera.extension.postMessage({action: 'received'});}
}
...
}

Kind Regards,
Stefan

30. November 2011, 01:16:50

spadija

Posts: 1643

I think you've got the right idea, though I'm not sure about your injected script. Unless you forgot the closing brace on the run() function, you are adding an event handler for window.onload which sends a message to the background script, but you only do that in the run() function. The run() function only gets called if the injected script gets a message from the background script, the background script only sends a message when it gets a message from the injected script, and the injected script only sends a message if run has been called. In other words, run() will never get called.

Also, I would suggest using addEventListener to attach events to the window. If a site relies on window.onload, changing it will break the site.

Is this what you want to do?
// background page

opera.extension.onmessage = function(e) {
	switch (e.data.action) {
		case 'tab loaded':
			// this will send back a response to the source tab
			e.source.postMessage({
				action: 'response',
				settings: { foo: 'bar' }, // your actual settings go here
			});
			break;
	}
}

// injected script

var settings = null;

if (window.top == window.self) {
	opera.extension.onmessage = function(e) {
		switch (e.data.action) {
			case 'response':
				// this runs when the background page responds
				settings = e.data.settings;
				run(e);
				break;	
		}
	}
	
	// you can also use 'DOMContentLoaded' instead of 'load' if you want the
	// event to run after the HTML is loaded but before images and other 
	// resources have finished downloading.
	window.addEventListener('load', function() {
		opera.extension.postMessage({ action: 'tab loaded' });
	}, false);
	
	function run(e) {
		...
	}
}

Forums » Dev.Opera » Opera Extensions Development Discussions