send a message from content script to popup script - javascript

i'm trying to send a message from my content script to my popup script because i need to use popup DOM when a page is loaded, here's what i tried :
contentScript.js
window.addEventListener("load", function() {
chrome.runtime.sendMessage({
"action": "init"
});
})
popup.js
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
if (request.action == "init") {
alert('Initialisation demandée...')
} else {
alert('Je n\'ai pas compris')
}
})
manifest.json
{
"manifest_version": 2,
"name": "Youtube color modifier",
"description": "Change youtube colors",
"version": "1.0",
"page_action": {
"default_icon": "icon.png",
"default_title": "Youtube color modifier",
"default_popup": "popup.html"
},
"permissions": [
"activeTab"
],
"content_scripts": [{
"matches": ["<all_urls>"],
"js": ["contentScript.js"]
}]
}
Thank you for helping a noob :))

If you have a content script, it will be run everytime you (re)load the page, assuming that the page you are visiting is registered in the manifest.json.
So instead of this:
window.addEventListener("load", function() {
chrome.runtime.sendMessage({
"action": "init"
});
})
simply try this:
chrome.runtime.sendMessage({
"action": "init"
});

Related

Rich Notification is not working

I'm currently working a chrome extension that will notify if the getElementId is not in the page.. and unfortunately the rich notification is not showing in contennt script. Should I use Message Passing for this?
load.js
con = document.getElementById('content');
if (con !=null){
var options = {
type:"basic",
title:"Error",
message:"Error",
iconUrl:"logo1.png"
}
chrome.notifications.create(options, callback);
function callback()
{
console.log('yey');
}
}
manifest.json
{
"manifest_version": 2,
"name": "CRM Online Chrome Extension",
"description": "License authentication key for the clients.",
"version": "1.0",
"background": {
"scripts": [
"background.js"
],
"persistent": true
},
"content_scripts":[
{
"matches":[ "*://*/*",
"*://*/*"
],
"js":["payload.js","load.js"]
}
],
"browser_action": {
"default_title": "Sample",
"default_icon": "logo1.png",
"default_popup": "popup.html"
},
"permissions": [
"notifications",
"tabs",
"*://*/*",
"*://*/*"
]
// "options_page": "option.html"
}
You have to send a message from your content script to the background page and this latter can create the notification upon the reception of the message.
For example:
background.js
chrome.runtime.onMessage.addListener(function(message){
if (message.value == "contentPresent"){ //if the message received is the one we sent from our content script
chrome.notifications.create({ //create notificacion
type:"basic",
title:"Error",
message:"Error",
iconUrl:"logo1.png"
}, function(){
console.log("yey");
});
}
});
content.js
if (document.getElementById("content")) { //if the element with id "content" is found...
chrome.runtime.sendMessage({value:"contentPresent"}); //send a message to the background script
}

For chrome extension, how can main.js call function from popup.js?

I have extracted username and password(main.js) from webpages and try to store them in indexeddb(popup.js). So far, the popup.html(popup.js) can store username and password manually. I want to call the function in popup.js when there are username and password. Thank you very much.
Function in main.js
if (username && password)
{
if(confirm("Store domain with username and password?"))
{
//want to call function test() from popup.js
}
else
{
}
}
Function in popup.js
function test()
{
alert("function called");
}
manifest.json
{
"name": "PM Extension",
"version": "1.0",
"manifest_version": 2,
"description": "a Google Chrome extension",
"permissions": ["tabs"],
"browser_action": {
"default_icon": "icon.png" ,
"default_title": "PM Extension",
"default_popup": "popup.html"
},
"content_scripts": [
{
"matches": ["http://*/*",
"https://*/*"
],
"js": ["jquery.min.js", "main.js"],
"run_at": "document_start"
}]
}
main.js
chrome.runtime.sendMessage('Your string/ object/ whatever', function(response) {
console.log(response.farewell);
});
popup.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request === 'What I want to recieve') {
// Do something
sendResponse('A response');
}
});
See the Massage Passing documentation.

Very simple Chrome Extension to display alert

I am trying to create a quick Chrome extension (complete beginner) and just want to display an alert whenever the icon is clicked, so I tried the following:
manifest.json
{
"name": "Something",
"version": "1.0",
"manifest_version": 2,
"description": "Woohoo",
"browser_action": {
"default_icon": "icon.png"
},
"content_scripts" : [{
"matches": ["<all_urls>"],
"js" : ["bgscript.js"]
}]
}
bgscript.js
chrome.browserAction.onClicked.addListener(function(tab) {
alert('icon clicked')
});
However when I click on my icon, nothing happens! Looking at the above - can anyone spot why this wouldn't work?
In order to be notified for browser-action's onClicked event, you need a background-page (or better yet event-page), not a content-script.
Change your manifest like this:
// Replace that:
"content_scripts" : [{...}]
// with this:
"background": {
"persistent": false,
"scripts": ["bgscript.js"]
}
If you want the browser-action to invoke something on a content-script, you need to communicate throught the background-page using Message Passing (e.g. Simple one-time requests).
E.g.:
manifest.json
{
"name": "Something",
"version": "1.0",
"manifest_version": 2,
"description": "Woohoo",
"browser_action": {
"default_icon": "icon.png"
},
"background": {
"persistent": false,
"scripts": ["background.js"]
},
"content_scripts" : [{
"matches": ["<all_urls>"],
"js" : ["content.js"]
}]
}
background.js
chrome.browserAction.onClicked.addListener(function (tab) {
/* Send a message to the active tab's content script */
chrome.tabs.sendMessage(tab.id, { action: 'saySomething' });
});
content.js
chrome.runtime.onMessage.addListener(function (msg) {
/* We received a message, let's do as instructed */
if (msg.action === 'saySomething') {
alert('something');
}
});

How can I call functions defined in a Chrome Extension from regular websites?

I'd like to make a website that is not part of the chrome plugin but rather just uses some API that the plugin exposes to it. Is this possible and if so, how do I do it? I googled this question and was unable to find anything.
I'm trying to use content scripts but nothing happens. Can someone explain what's wrong here?
manifest.json
{
"manifest_version": 2,
"name": "Hello World Extension",
"description": "This extension prints hello world.",
"version": "1.0",
"background": {
"page": "background.html"
},
"browser_action": {
"default_icon": "img/icon.png",
"default_popup": "popup.html"
},
"content_scripts": [
{
"matches": ["http://locahost:8888/*"],
"js": ["EmotivAPI.js"]
}
]
}
EmotivAPI.js
var port = chrome.runtime.connect();
console.log("Hello?");
window.addEventListener("message", function (event) {
// We only accept messages from ourselves
if (event.source != window)
return;
if (event.data.type && (event.data.type == "FROM_PAGE")) {
console.log("Content script received: " + event.data.text);
port.postMessage(event.data.text);
alert("recieved!");
}
}, false);
js in the webpage
window.sayHello = function () {
window.postMessage({ type: "FROM_PAGE", text: "Hello from webpage!" }, "*");
}
console.log('Emotiv extension loaded.');
}
I'm calling window.sayHello() from the console
Content Scripts can help you in this case.
The content script will be injected into a page:
"content_scripts": [
{
"matches": ["http://www.google.com/*"], // try with "http://localhost:*/*" or "http://localhost:*"
"css": ["mystyles.css"],
"js": ["content_script.js"]
}
]
If you want to inject the code only sometimes, use the permissions field instead
/* in manifest.json */
"permissions": [
"tabs", "http://*/*"
],
In you extension html file, you can then execute the script by:
chrome.tabs.executeScript(null, {file: "content_script.js"});

I don't understand Google Chrome extensions. Please help.

I want to do something that seems like it should be fairly simple, but I can't get it to work.
All I want it to do is when the button in the popup is clicked I want to log the word "Hello" to the console. At the moment nothing happens. No error message. Just nothing.
Here is my manifest.jason file
{
"name": "Content Script",
"version": "1.0",
"description": "Experiments with content scripts.",
"permissions": [
"tabs", "http://*/*", "https://*/*"
],
"browser_action": {
"default_icon": "icon.png",
"popup": "popup.html"
}
}
Here is my popup.html
<h1>Hello</h1>
<script>
function changeField() {
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.sendRequest(tab.id, {"code": "sayHello"});
});
}
</script>
<button onclick="changeField();">Click</button>
Here is my contentscript.js
function sayHello() {
console.log("Hello");
}
chrome.extension.onRequest.addListener(
function(request, sender, response) {
if(request.code == 'sayHello') {
sayHello();
}
}
);
I've been reading the docs but they seem to skip over a lot of things. If someone could explain why this doesn't work I would be eternally grateful.
You didn't inject your content script to the page which console lives in.
Add content_scripts segment to your manifest.json file.
There is a reference of manifest.json file on chrome extension official site.
{
"name": "Content Script",
"version": "1.0",
"description": "Experiments with content scripts.",
"permissions": [
"tabs", "http://*/*", "https://*/*"
],
"browser_action": {
"popup": "popup.html"
},
"content_scripts":[{
"matches":["http://*/*"],
"js":["content_script.js"]
}]
}

Categories