Reputation: 538
In background.js, I create a popup like so:
chrome.windows.create({
focused: true,
width: 1170,
url : "settings/index.html",
type: "popup"
}, function(popup) {
tab_app = popup.id;
alert(tab_app);
});
I store the id in tab_app.
how can I pass a value from background.js to my popup?
I'm trying like that:
chrome.tabs.executeScript(tab_app, {code: "alert("+message.add+");"});
but it keeps telling me that this tab id doesnt exist.. im assuming its because its a popup. will appreciate some help.
Upvotes: 1
Views: 1101
Reputation: 77523
Since it's your extension page, the method of choice is Messaging.
Note: you can't use the per-tab messaging of chrome.tabs.sendMessage
, since this explicitly targets the content script context (that doesn't exist for extension pages). You need to use the "broadcast" chrome.runtime.sendMessage
that will send to all other extension pages.
If you can have more than one popup-type window at a time, this may be a problem - you need some identifier to go along. You could pass it as a URL parameter or a URL hash, e.g. "settings/index.html?id=foo"
or "settings/index.html#foo"
. If you don't expect more than one popup-type window (you can always check if one is open before opening a new one), it doesn't matter.
If you really need dynamic code loading or execution, not just passing data (doubtful), you need to be mindful of CSP.
<script>
tag to the document.eval
it in the extension context. You could add 'unsafe-eval'
to CSP string, but that's a bad idea in general.This old answer of mine may be of use - I'm using opening a new tab and passing data there to print it.
Upvotes: 1
Reputation: 7156
You cannot call executeScript
in the your extension
pages. If you try to use executeScript
in your extension page. It will show error :
Unchecked runtime.lastError while running tabs.executeScript: Cannot access contents of url "chrome-extension://extension_id/yourPage.html". Extension manifest must request permission to access this host
Now you cannot add "chrome-extension://<extension_id>/yourPage.html"
under permissions
in manifest.json
because it is invalid and not allowed.
Instead you can use message passing
.
background.js:
function createNewtab(){
var targetId = null;
chrome.tabs.onUpdated.addListener(function listener(tabId, changedProps) {
if (tabId != targetId || changedProps.status != "complete")
return;
chrome.tabs.onUpdated.removeListener(listener);
chrome.tabs.sendMessage(targetId, {message : "loadNewTab"},function(response){
// do nothing yet
});
});
chrome.windows.create({
focused: true,
width: 1170,
url : chrome.extension.getURL("settings/index.html"),
type: "popup"
}, function(popup) {
targetId = popup.tabs[0].id;
});
}
index.js:
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){
switch (request.message){
case "loadNewTab":
alert("HI")
break;
}
});
Upvotes: 0