console.log doesn't work from chrome.tabs.executeScript - javascript

I need to execute script once user clicked my context menu item.
So for the purpose I created the context menu from my background js:
chrome.contextMenus.create({"title": title, "contexts": contexts,
"onclick": genericOnClick});
It appears as expected. Later on from the genericOnClick I try to execute my script:
chrome.tabs.executeScript(null, {code: "console.log('test 1');"}, function() {
console.log("test 2");
});
I can see that the "test 2" is printed to console but "test 1" never gets printed. What am I doing wrong?
I've tried adding the console.log sentence to a separate js file but it failed to print it as well:
chrome.tabs.executeScript(null, {"file": 'content_script.js'}, function() {
console.log("test 2");
});
Note: my content_script.js is not defined in manifest. My manifest looks like follows:
{
"name": "My First Extension",
"version": "1.0",
"manifest_version": 2,
"description": "Sample extension",
"page_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": [
"http://*/*",
"https://*/*",
"tabs",
"contextMenus"
],
"background": {
"scripts": ["sample.js"]
},
"icons": {
"16": "icon16.png"
}
}
Thank you in advance.

The only piece of code from your extension that has access to the console is the content script that is injected into the original page.
From your code it looks like you are trying to write to the console from a background script. So, to write to the console from a background page you've to inject a content script to do the job for you.
In my extensions I use my own function to write messages to the console from a background script. The code for the same is given below:
function logMessage(msg){
chrome.tabs.executeScript({code:"console.log('"+msg+"')"});
}
Define the above as the first function in your background script and call it from anywhere in the background script to write messages to the console.
In your case you can use this from the genericOnClick function to write messages to the console.

// addListener
chrome.browserAction.onClicked.addListener(function() {
chrome.tabs.executeScript(null, {file: "content_script.js"}, function() {
console.log("test 2");
});
});
// Context Menu
chrome.contextMenus.create({
title: myTitle,
contexts: ['page'],
onclick: function (detail, tab) { fn(tab) }
});
so;
"permissions": [
"tabs", "http://*/*", "https://*/*"
]
chrome.tabs.executeScript(null,{code:"document.body.style.backgroundColor='red'"});
or:
// Functional structure
function hi() { alert("hi"); };
// hi function toString after run function (hi)()
chrome.tabs.executeScript(null, { code: "(" + hi.toString() + ")()" });

Related

Unable to receive message on tab from background script

I wrote this script to send a message from a background script to a script in a new tab but for some reason, the script in the tab isn't receiving the message. Is this a problem with my script or my browser (Firefox 62.0.3)
my "manifest":
{
"manifest_version":2,
"name": "test",
"version": "1.0",
"description": "this is a test extension",
"background":{
"scripts": ["OnButtonClick.js"]
},
"permissions": [
"tabs"
],
"content_scripts": [{
"matches": ["www.youtube.com"],
"js": ["input.js"]
}],
"browser_action": {
"default_icon": "button.png",
"default_title": "test button"
}
}
my "OnButtonClick.js":
function action(){
browser.tabs.create({
url: "www.youtube.com"
});
browser.tabs.sendMessage(1,{"message":"hi"})
}
browser.browserAction.onClicked.addListener(action);
and my "input.js":
function handleMessage(msg){
console.log(msg);
}
browser.runtime.onMessage.addListener(handleMessage)
browser.tabs.create() is a asynchronous therefore, browser.tabs.sendMessage() runs even before a tab is created.
You have to wait for it to run first.
Here are some suggestions:
// first create the tab
const newTab = browser.tabs.create({
url: 'https://example.org'
});
newTAb.then(onCreated, onError);
// after tab is created
function onCreated(tab) {
browser.tabs.sendMessage(tab.id,{message: 'hi'});
}
// in case of error
function onError(error) {
console.log(`Error: ${error}`);
}
// above can also be written as this
browser.tabs.create({
url: 'https://example.org'
}).then(
tab => browser.tabs.sendMessage(tab.id,{message: 'hi'}),
error => console.log(error)
);
// another alternative for above
browser.tabs.create({url: 'https://example.org'})
.then(tab => browser.tabs.sendMessage(tab.id,{message: 'hi'}))
.catch(error => console.log(error));
// Using chrome and callback function
chrome.tabs.create({url: 'https://example.org'}, tab =>
browser.tabs.sendMessage(tab.id,{message: 'hi'})
);
// same as above, all with chrome
chrome.tabs.create({url: 'https://example.org'}, tab =>
chrome.tabs.sendMessage(tab.id,{message: 'hi'})
);
You can also use async/await but that may make it more complicated in this case.
Update on comment:
content_scripts by default run at "document_idle" (corresponds to complete. The document and all its resources have finished loading.)
"content_scripts": [{
"matches": ["www.youtube.com"],
"js": ["input.js"]
}],
Therefore, the input.js is injected once everything is loaded. However, the sendMessage() runs as soon as tab is created and thus there is no listener to listen to its message.
In your simple example, that can be fixed by "run_at": "document_start"
"content_scripts": [{
"matches": ["www.youtube.com"],
"js": ["input.js"],
"run_at": "document_start"
}],
However, if input.js needs to access DOM after receiving message, then you need to add a DOMContentLoaded or load listener and run it after the document is loaded.
why do you want to use "sendMessage"?
you can use this code
browser.tabs.executeScript(tabID, { code: "func()" /* your function in content script*/,frameId:0 /* for send to all frame or put id for use a special frame id*/});
or this code as file
browser.tabs.executeScript(tabID, { file: "/filename.js",frameId:0});

How to Access / Read any Text / Tag Value from the Webpage using Chrome Extension

I am writing my First Chrome Plugin and I just want to get some text present on the current webpage and show it as a alert when i click the Extension. Lets say I am using any any webpage on www.google.com after some Search query, Google shows something like "About 1,21,00,00,000 results (0.39 seconds) " . I want to show this Text as an alert when i execute my plugin. This is what i am doing.
here is the manifest.json that i am using
{
"manifest_version": 2,
"name": "Getting started example",
"description": "This extension shows a Google Image search result for the current page",
"version": "1.0",
"background": {
"persistent": false,
"scripts": ["background.js"]
},
"content_scripts": [{
"matches": ["*://*.google.com/*"],
"js": ["content.js"]
}],
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": [
"activeTab"
]
}
Here is my popup.js
document.addEventListener('DOMContentLoaded', function() {
document.getElementById("checkPage").addEventListener("click", handler);
});`
function handler() {
var a = document.getElementById("resultStats");
alert(a.innerText); // or alert(a.innerHTML);
}
Here is my content.js
// Listen for messages
chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
// If the received message has the expected format...
if (msg.text === 'report_back') {
// Call the specified callback, passing
// the web-page's DOM content as argument
sendResponse(document.all[0].outerHTML);
}
});
Here is my background.js
var urlRegex = /^https?:\/\/(?:[^./?#]+\.)?google\.com/;
// A function to use as callback
function doStuffWithDom(domContent) {
console.log('I received the following DOM content:\n' + domContent);
}
// When the browser-action button is clicked...
chrome.browserAction.onClicked.addListener(function (tab) {
// ...check the URL of the active tab against our pattern and...
if (urlRegex.test(tab.url)) {
// ...if it matches, send a message specifying a callback too
chrome.tabs.sendMessage(tab.id, {text: 'report_back'}, doStuffWithDom);
}
});
1) run content scrip after document ready ** check "run_at"
"content_scripts": [{
"run_at": "document_idle",
"matches"["*://*.google.com/*"],
"js": ["content.js"]
}],
2) on click of extension make another js to run( popup js). The popup js has access to the ( open page document)
// A function to use as callback
function doStuffWithDom() {
//console.log('I received the following DOM content:\n' + domContent);
//get tabID when browser action clicked # tabId = tab.id
chrome.tabs.executeScript(tabId, {file: "js/popup.js"});
}
3) In popup JS simple you can set alert
var a = document.getElementById("resultStats");
alert(a.innerText); // or alert(a.innerHTML);
Just remove "default_popup" part in manifest.json, as you have listened to chrome.browserAction.onClicked event in background page. They can't live at the same time.

Getting DOM in Chrome extension popup?

I'm trying to create a Chrome extension that displays the current page's DOM in a popup.
As a warmup, I tried putting a string in getBackgroundPage().dummy, and this is visible to the popup.js script. But, when I try saving the DOM in getBackgroundPage().domContent, popup.js just sees this as undefined.
Any idea what might be going wrong here?
I looked at this related post, but I couldn't quite figure out how to use the lessons from that post for my code.
Code:
background.js
chrome.extension.getBackgroundPage().dummy = "yo dummy";
function doStuffWithDOM(domContent) {
//console.log("I received the following DOM content:\n" + domContent);
alert("I received the following DOM content:\n" + domContent);
//theDomContent = domContent;
chrome.extension.getBackgroundPage().domContent = domContent;
}
chrome.tabs.onUpdated.addListener(function (tab) {
//communicate with content.js, get the DOM back...
chrome.tabs.sendMessage(tab.id, { text: "report_back" }, doStuffWithDOM); //FIXME (doesnt seem to get into doStuffWithDOM)
});
content.js
/* Listen for messages */
chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
/* If the received message has the expected format... */
if (msg.text && (msg.text == "report_back")) {
/* Call the specified callback, passing
the web-pages DOM content as argument */
//alert("hi from content script"); //DOESN'T WORK ... do we ever get in here?
sendResponse(document.all[0].outerHTML);
}
});
popup.js
document.write(chrome.extension.getBackgroundPage().dummy); //WORKS.
document.write(chrome.extension.getBackgroundPage().domContent); //FIXME (shows "undefined")
popup.html
<!doctype html>
<html>
<head>
<title>My popup that should display the DOM</title>
<script src="popup.js"></script>
</head>
</html>
manifest.json
{
"manifest_version": 2,
"name": "Get HTML example w/ popup",
"version": "0.0",
"background": {
"persistent": false,
"scripts": ["background.js"]
},
"content_scripts": [{
"matches": ["<all_urls>"],
"js": ["content.js"]
}],
"browser_action": {
"default_title": "Get HTML example",
"default_popup": "popup.html"
},
"permissions": ["tabs"]
}
You got the syntax of chrome.tabs.onUpdated wrong.
In background.js
chrome.tabs.onUpdated.addListener(function(id,changeInfo,tab){
if(changeInfo.status=='complete'){ //To send message after the webpage has loaded
chrome.tabs.sendMessage(tab.id, { text: "report_back" },function(response){
doStuffWithDOM(response);
});
}
})

Google Chrome Tabs Execute Script

I'm trying to develop a google chrome extension that scrape out specific data from the page once the page is finished loading. I'm trying to achieve it by executing a javascript file by setting file : 'js/scrape.js' and runAt: 'document_idle'.
However, setting selected : false does work but selected : true doesn't.
index.js:
var crawler = function() {
return {
init : function() {
document.getElementById('open').addEventListener('click', this.open);
},
open : function() {
var url = document.getElementById('url').value;
chrome.tabs.create({
url : url,
selected : true //doesn't work, setting to false does work
}, function(tab) {
chrome.tabs.executeScript(tab.id, {
file : 'js/scrape.js',
runAt : 'document_idle'
});
});
}
}}()
document.addEventListener('DOMContentLoaded', function() {
crawler.init();
});
I included index.js inside popup.html:
<script type="text/javascript" src="index.js"></script>
Finally, manifest.json:
{
"manifest_version": 2,
"name": "Crawler",
"description": "Scrape out the crap.",
"version": "1.0",
"permissions": ["tabs", "http://*/*", "https://*/*"],
"browser_action": {
"default_title": "Scrape out the crap",
"default_icon": "icon.png",
"default_popup": "popup.html"
}
}
Using active => true fixed the issue. I missed the part of the documentation that explains it.

chrome - How to display images in popup.html using dom and js

I am doing a project and I need to display on a chrome extension popup all the images of the current selected tab website, I tried many things but the popup always shows as a small popup with nothing on it.
Here is the code:
Dom.js:
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if (request.action == "getDOM")
sendResponse({dom: document.body.getElementsByTagName("img")});
else
sendResponse({}); // Send nothing..
});
Manifest.json:
{
"manifest_version": 2,
"name": "PrintIt",
"version": "1.0",
"description": "Partilha conteudo com redes sociais",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": [
"tabs"
],
"content_scripts": [{
"matches": [
"http://www.google.com/*"
],
"js": [
"dom.js"
]
}]
}
Popup.html:
<html>
<head>
<script>
chrome.tabs.getSelected(null, function(tab) {
// Send a request to the content script.
chrome.tabs.sendRequest(tab.id, {action: "getDOM"}, function(response) {
document.write(response.dom);
});
});
</script>
</head>
<body>
</body>
</html>
I did console.log(response.dom) and i got the folowing errors in estension console:
Port error: Could not establish connection. Receiving end does not exist. miscellaneous_bindings:236
chromeHidden.Port.dispatchOnDisconnect miscellaneous_bindings:236
Error in event handler for 'undefined': Cannot read property 'dom' of
undefined TypeError: Cannot read property 'dom' of undefined
at chrome-extension://cfboppmcojfddlkbpohfnnnkogpeflgk/popup.js:4:23
at miscellaneous_bindings:281:11
at chrome.Event.dispatchToListener (event_bindings:390:21)
at chrome.Event.dispatch_ (event_bindings:376:27)
at chrome.Event.dispatch (event_bindings:396:17)
at Object.chromeHidden.Port.dispatchOnDisconnect (miscellaneous_bindings:239:27) event_bindings:380
I run into the same problem some time ago. It's simply prohibited to place script code inside the popup.html so it's not working. Place your code completely inside of dom.js and everything should be fine.

Categories

Resources