0

I have a gwt project that wrap in chrome extensions.

In GWT, I export a java method to jsni called:

Java Method: sendMessage(String msg);
export jsni: $wnd.sendMessage = function(msg) { ... };

then in chrome extension, I execute:

chrome.tabs.executeScript(tabId, {code: "sendMessage('hello');"}

but not thing happened, I've tried:

chrome.tabs.executeScript(tabId, {code: "alert('hello');"}

and it just works fine. but it just can't call my gwt jsni method.

2 Answers2

0

Chrome content scripts exist in an isolated world.

$wnd.sendMessage is exported in the page context, and not accessible from a content script.

You'll need to inject code into the page itself (with a <script> tag) to access it.

See this canonical question on the topic, and this question can also be of use: Executing code at page-level from Background.js and returning the value

Community
  • 1
  • 1
Xan
  • 74,770
  • 16
  • 179
  • 206
  • thank you @Xan, I have successful call JSNI method in background.js, but I have another question that I don't know how to pass a json format string in it. while I pass "sendMessage(123);" it works, but not work when I pass "sendMessage(jsonString);" – Neil Tseng Jan 18 '15 at 04:32
0

solved the problem, when pass a json string, you have to encode the string to prevent double quotes/special character in the string, here is my code:

assume the data format is:

var data = '{"abc":123,"cde":"kkk"}';

then encode the data:

var param = '\'' + encodeURIComponent(data) + '\'';

put then data into the code to execute:

var codeToExec = [
        'var actualCode = "window.sendMessage(' + param + ');"',
        'var script = document.createElement("script");',
        'script.textContent = actualCode;',
        '(document.head||document.documentElement).appendChild(script);',
        'script.remove();'
    ].join('\n');

chrome.tabs.executeScript(mainTabId, {code: codeToExec});