Pabi Pabi - 4 months ago 12
Javascript Question

Scipt not Executing in Selected Tab to Send and Receive Messages

I am having trouble making a script run on a page.

Here is what my background.js looks like:

chrome.tabs.query({
url: 'https://www.tradingview.com/*'
}, function(tabs) {
if (tabs.length == 1) {
var tabURL = tabs[0].url;
alert(tabURL);
alert(tabs[0].id);
chrome.tabs.executeScript(tabs[0].id, {file: "getTradingData.js"}, function(){
chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
console.log(response.farewell);
});
});
} else {
alert("Please have one and only one tradingview chart page opened.");
}
});


chrome.tabs.executeScript(tabs[0].id, {file: "getTradingData.js"}
should be executing the script getTradingData.js but I don't think it is. I have an alert in the script that is not running, but does run as content script when I refresh the page.

Here is what ny getTradingData.js looks like:
alert("getTradingData.js is Running");

var myPort = chrome.extension.connect();

chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
alert("got message");
if (request.subject == "getPrice")
sendResponse({
msg: price
});
});


Finally here is my manifest.json:

{
"manifest_version": 2,

"name": "Automated TradingView Strategy",
"description": "This extension shows a Google Image search result for the current page",
"version": "1.0",

"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"background": {
"scripts": ["jquery-2.2.3.min.js", "background.js"]
},
"content_scripts": [
{
"matches": ["https://www.tradingview.com/chart/*", "http://www.tradingview.com/*"],
"js": ["jquery-2.2.3.min.js", "getTradingData.js"]
}
],
"permissions": [
"activeTab",
"tabs",
"https://ajax.googleapis.com/"
]
}


I need to be able to send data between "tradingview.com/chart/*" and the extension background.js. However, the script is not loading when I refresh the extension so it can't receive nor send messages.

Let me know what I am doing wrong.

Answer

To run the getTradingData.js using executeScript you must add the address of the site in permissions.

"permissions": ["*://*.tradingview.com/*", "tabs"]

From background you send {greeting: "hello"}, but you do not accept these data in getTradingData.js. Therefore you do not get response.

console.log(response.farewell);

You do not send response.farewell. They will not be displayed.


if (request.subject == "getPrice") {

    sendResponse({msg: price});
}

Same. You get alerts only.

Programmatic injection