当前位置: 动力学知识库 > 问答 > 编程问答 >

Chrome Ext Open Tab and Send Message to Content Script of Newly Created Tab

问题描述:

I am trying to open a new tab in my chrome extension from the popup (which is working) and then also pass a message to the content script that will be injected into the newly opened tab. This code is being called in my popup.js after a button is clicked within the popup.

The tab is opening as expected, but the content script is not executing as expected. I am trying to tap into the callback function of the create method. The code inside the of the callback has been tested separately and works as expected when standing alone, I just cannot figure out how to bring these to things together properly. I thought maybe this was happening b/c the content script wasn't loaded yet, so I tried somethings to wait until the tab loaded with no luck. Below is the code I have been working on.

$("#submit_button").click(function() {

chrome.tabs.create({url: "http://myurl.com", index: 0}, function(tab) {

chrome.tabs.sendMessage(tab.id, {"value": "amazon_paste", "object": chrome.extension.getBackgroundPage().jsonOrderObj});

});

});

Here is working code after commenting out the create tab and manually going to the url:

//chrome.tabs.create({url: "http://myurl.com", index: 0}, function(tab) {

chrome.tabs.getSelected(null, function(tab) {

chrome.tabs.sendMessage(tab.id, {"value": "amazon_paste", "object": chrome.extension.getBackgroundPage().jsonOrderObj});

});

//});

Also here is my JSON manifest:

{

"name": "Amazon Order Extension",

"version": "2.0",

"manifest_version": 2,

"content_scripts": [

{

"matches": ["https://sellercentral.amazon.com/gp/orders-v2/confirm-shipment/*"],

"js": ["jquery.js", "amazon_content_script.js"]

},

{

"matches": ["http://myurl.com"],

"js": ["jquery.js", "inventory_content_script.js"]

}

],

"permissions": ["background", "tabs"],

"background": {

"page": "background.html"

},

"description": "",

"browser_action": {

"default_icon": "icon.png",

"default_popup": "popup.html"

}

}

网友答案:

For "external" sites, it looks like you should have an "externally_connectable" key in your manifest.json:

"externally_connectable": {
  "matches": [
    "*://*.example.com/*"
  ]
}

Does adding this in work for you?

Source: http://developer.chrome.com/extensions/messaging#external-webpage

分享给朋友:
您可能感兴趣的文章:
随机阅读: