I want to call a function in the chrome.tabs.executeScript
that returns a string that I will be sending it in chrome.runtime.sendMessage()
.
code:
chrome.tabs.executeScript(tab.id, {code:var string1= ??? ;
chrome.runtime.sendMessage(string1);"});
How do I do this . My function contains Javascript code that returns a string or an array of strings.
Some help would be appreciated.
Update:
function(array_of_Tabs) {
var tab = array_of_Tabs[0];
//tab.url; - url of the active tab
chrome.tabs.executeScript(tab.id, {code: 'var test = document.body,text= test.textContent,bodyStart="<BODY",bodyEnd="</BODY>",regex=bodyStart+"(.*?)"+ bodyEnd,regexg = new RegExp(regex, "g"),match = regexg.exec(text);' + 'chrome.runtime.sendMessage(match);'});
});
chrome.runtime.onMessage.addListener(function(request) {
document.getElementsByTagName('html')[0].innerHTML = request;
});
This should've worked according to what you told me, But doesn't . Why.?
And yes BTW I am not parsing pure html on the page it may be anything say to for that matter.
I want to call a function in the chrome.tabs.executeScript
that returns a string that I will be sending it in chrome.runtime.sendMessage()
.
code:
chrome.tabs.executeScript(tab.id, {code:var string1= ??? ;
chrome.runtime.sendMessage(string1);"});
How do I do this . My function contains Javascript code that returns a string or an array of strings.
Some help would be appreciated.
Update:
function(array_of_Tabs) {
var tab = array_of_Tabs[0];
//tab.url; - url of the active tab
chrome.tabs.executeScript(tab.id, {code: 'var test = document.body,text= test.textContent,bodyStart="<BODY",bodyEnd="</BODY>",regex=bodyStart+"(.*?)"+ bodyEnd,regexg = new RegExp(regex, "g"),match = regexg.exec(text);' + 'chrome.runtime.sendMessage(match);'});
});
chrome.runtime.onMessage.addListener(function(request) {
document.getElementsByTagName('html')[0].innerHTML = request;
});
This should've worked according to what you told me, But doesn't . Why.?
And yes BTW I am not parsing pure html on the page it may be anything say to for that matter.
chrome.tabs.executeScript
has a third, optional argument that has access to the result of your injected code. E.g.
// In `background.js`:
...
const tab = ...
chrome.tabs.executeScript(
tab.id,
{code: 'const string1 = "Hello, world!"; return string1;'},
resultArr => processString1(resultArr[0]));
function processString1(str1) {
alert(`String1 = "${str1}"`);
}
If this does not cover your needs and you still want to use Message Passing:
// In `background.js`:
...
const tab = ...
chrome.tabs.executeScript(
tab.id,
{
code: 'const string1 = "Hello, world!"; ' +
'chrome.runtime.sendMessage({text: string1});',
});
chrome.runtime.onMessage.addListener(msg => {
if (msg.text !== undefined) {
alert(`String1 = "${msg.text}"`);
}
});