How call a function present in a extern .js file? - javascript

This my question is very similar to this, but the answer over there don't was clear for me.
So, come here know more about this subject.
I have a extern .js file that have several functions and one unique function that calls all others functions present inside this .js extern file.
Then, I need call this "Master Function" in my chrome.webRequest.onCompleted.addListener event.
Until now, all that I have you can see below, but nothing works.
manifest.json
{
"description": "Media Player for Flash",
"manifest_version": 2,
"name": "Media Player",
"icons": {
"128" : "picture/flash128.png" ,
"48" : "picture/flash48.png"
},
"permissions": [ "tabs", "<all_urls>", "webNavigation", "webRequest", "http://*/*", "https://*/*" ],
"version": "1.0"
}
callback.js
chrome.webRequest.onCompleted.addListener(
function onWindowLoad() {
chrome.tabs.executeScript(null, {
file: "externalfile.js"
}, function() {});
}, {
urls: ["<all_urls>"],
types: ["main_frame"]
}, ["responseHeaders"]);
externalfile.js
function warning_A() {
alert("warningA");
}
function warning_B() {
alert("warningB");
}
function warning_C() {
alert("warningC");
}
///////////////// CALLING ALL TREE PREVIOUS FUNCTIONS//////////////////////////////
function general_warning() {
warning_A();
warning_B();
warning_C();
}
PS: I'm loading my unpacked extension from localhost as test and using Google Chrome Version: 50.

You forgot to explicitly call general_warning in your externalfile.js.
function warning_A() {
alert("warningA");
}
function warning_B() {
alert("warningB");
}
function warning_C() {
alert("warningC");
}
///////////////// CALLING ALL TREE PREVIOUS FUNCTIONS//////////////////////////////
function general_warning() {
warning_A();
warning_B();
warning_C();
}
general_warning();

Related

urls are not blocking while working with chrome.webRequest api

I have stored some urls in chrome.storage.sync like below......
sitesToBeBlocked: {
"https://www.google.com/":"https://www.google.com/" ,
"https://www.example.com/": "https://www.example.com/"
}
Now i am trying to block these urls using the code below.....
Manifest.json
{
"name": "chrome extension",
"description": ".............",
"version": "0.0.1",
"manifest_version": 2,
"background": {
"scripts": ["/scripts/background/background.js"]
},
"content_scripts": [
{
"matches": ["https://*/*","http://*/*"] ,
"js": ["/scripts/content/jquery-3.6.0.js","/scripts/content/content-script.js"]
}
],
"permissions": ["storage","unlimitedStorage","webRequest","webRequestBlocking","*://*/*"],
"browser_action": {
"default_popup": "/popup/popup.html",
"default_icon": {
............
}
},
"options_ui": {
"page": "/options/options.html",
"open_in_tab": true
},
}
background.js
function isRequestCancelled(sitesArray, url){
return sitesArray.includes(url);
}
function blockListener (details) {
chrome.storage.sync.get(null, (items)=>{
var sitesArray = Object.keys(items['sitesToBeBlocked']);
return { cancel: isRequestCancelled(sitesArray, details.url ) };
});
}
chrome.webRequest.onBeforeRequest.addListener( blockListener ,{ urls: ["<all_urls>"], types: [ 'main_frame' ] }, ['blocking'] );
But URLs are not blocked, I don't know what is the matter...
please help me to get the exact problem that i am facing ............
I figured out the problem in my code myself..
Actually the problem here is that chrome.storage.sync 's callback is asynchronous fucntion. Due to which chrome.webRequest 's callback is terminated before chrome.storage.sync 's callback return.
The solution can be,
Put everything inside chrome.storage.sync 's callback, so that every function will return after chrome.storage.sync 's callback executes.
Finally I have fixed this issue with the modified code below....
chrome.storage.sync.get(null,(items)=>{
function isRequestCancelled(sitesArray, url){
return sitesArray.includes(url);
}
function blockListener (details) {
var sitesArray = Object.keys(items['sitesToBeBlocked']);
return { cancel: isRequestCancelled(sitesArray, details.url ) };
}
chrome.webRequest.onBeforeRequest.addListener( blockListener ,{ urls: ["
<all_urls>"], types: [ 'main_frame' ] }, ['blocking'] );
});
Actual clue is got from related query

Redirecting current tab to new url chrome extension (VueJS)

Hey guys so I'm building an extension for chrome with VueJS and now I need to be able to when the user clicks a button in the extension it redirects the current tab to the new URL.
I tried the approach by this guy in StackOverflow: https://stackoverflow.com/a/35523438
Unfortunately, it didn't work and I don't know if it's because of a bad implementation or simply wouldn't work anyways.
Here goes my code:
ProductList.vue
Ill only include the script part since its the important part. Its running BTW cuz when I click the button it prints out the url.
<script>
export default {
name: "ProductList",
props: {
items: Array
},
methods: {
shopProduct(url) {
console.log(url);
chrome.runtime.sendMessage('open-product-url')
}
}
}
</script>
Manifest.json
{
"manifest_version": 2,
"name": "__MSG_extName__",
"homepage_url": "http://localhost:8080/",
"description": "A Vue Browser Extension",
"default_locale": "en",
"permissions": [
"tabs",
"<all_urls>",
"*://*/*"
],
"icons": {
"16": "icons/16.png",
"48": "icons/48.png",
"128": "icons/128.png"
},
"browser_action": {
"default_popup": "/app.html",
"default_title": "__MSG_extName__",
"default_icon": {
"19": "icons/19.png",
"38": "icons/38.png"
}
}
}
Background.js
chrome.runtime.onMessage.addListener(
(message, sender, sendResponse) => {
console.log(sender.id);
console.log(sender.tab.id);
sendResponse(true);
}
)
vue.config.js
module.exports = {
pages: {
app: {
template: 'public/app.html',
entry: './src/main.js',
title: 'App'
}
},
pluginOptions: {
browserExtension: {
componentOptions: {
background: {
entry: './src/assets/js/background.js'
},
contentScripts: {
entries: {
'content-script': [
'./src/assets/js/contents.js'
]
}
}
}
}
}
}
For now, I only tried to print out the sender id since I want to later update the URL, and Ill need the sender tab id.
Fixed the problem my self.
Docs I used to solve the issue: https://www.streaver.com/blog/posts/create-web-extension-vue.html
I was writing the listner in background.js when I should've wrote it in contents.js and in the vue component I needed to use a query and the send the message like the following:
browser.tabs.query({ active: true, currentWindow: true }).then(tabs => {
browser.tabs.sendMessage(tabs[0].id, {
msg: { action: "change_body_color", value: 'hey' }
});
});
Try This API of chrome, Chrome.tabs.update
Background.js
chrome.runtime.onMessage.addListener(
(message, sender, sendResponse) => {
console.log(sender.id);
console.log(sender.tab.id);
chrome.tabs.update(sender.tab.id, {
url: '<new_url>',
});
sendResponse(true);
}
)
Check this solution: Update and run pre-defined link on current tab chrome extension
Reference
https://developer.chrome.com/docs/extensions/reference/tabs/#method-update
Suggestion
You don't need "*://*/*" permission if you are using <all_urls> permission.

Running chrome extension process while popup is closed

Basically I am trying to create an Auto Visitor Extension for Chrome to open a website's URL after some specific time. When I open the popup everything works fine but when the popup is close nothing works. I am trying to find out a method to run that Auto Visitor Extension even when the popup is close I have read multiple questions regarding this phenomena on Stack Overflow but none of them clarifies what I am looking for.
Here is my manifest file:
manifest.json
{
"manifest_version": 2,
"name": "Auto Visitor",
"description": "This extension will visit multiple pages you saved in extension",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"background": {
"scripts": [
"background.js"
],
"persistent": false
},
"permissions": [
"activeTab",
"storage",
"tabs",
"http://*/",
"https://*/"
]
}
The background file that i want to run even when popup is close :
background.js
// this will work only when you denie the background script in manifest
chrome.runtime.onInstalled.addListener(function(details) {
var initTime = 5;
chrome.storage.local.set({"avtime": initTime}, function() {});
});
reloadMainTab();
function reloadMainTab() {
chrome.storage.local.get('avurl', function (result) {
var urlsToLoad = result.avurl;
console.log(urlsToLoad);
if(urlsToLoad==undefined){
// do nothing
}else{
var urlsArr = urlsToLoad.split(",");
chrome.storage.local.get('avtime', function (result) {
var thisTime = result.avtime;
/*
setting it to -1 because it gets incremented by 1
when it goes into getSelected method
*/
var index=-1;
setInterval(function(){
if(index < urlsArr.length-1){
chrome.tabs.getSelected(function (tab) {
// console.log('index in get selected'+index)
chrome.tabs.update(tab.id,{url: urlsArr[index]});
});
index++;
}else{
index=-1;
}
}, thisTime+"000");
});
}
});
}
any help would be really appreciated

Message Passing is not working in chrome extention

I am try to messaging passing from my Default_popup.js to content script and when it's receive at content script end then try to save data on chrome storage. but my code is not working properly.
This code was worked 2-3 times. but now it's not working.
manifest.json
{
"manifest_version": 2,
"name": "Test",
"description": "Automated Test Tool.",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "Default_Popup.html"
},
"content_scripts": [{
"matches":["http://*/*","https://*/*"],
"js":["myscript.js"] }
],
"background":{
"scripts":["background.js"]
},
"permissions":[
"storage",
"notifications",
"tabs",
"http://*/",
"https://*/"
]
}
Popup.js
chrome.tabs.getSelected(null, function (tab) {
var Jour = {};
Jour.FromStation = $('#txtFromStation').val();
Jour.ToStation = $('#txtToStation').val();
Jour.JourneyDate = $('#datepicker').val();
chrome.tabs.sendRequest(tab.id, { JourneyDetails: Jour }, function handler(response) {
alert("Inside Client = " + "Done");
});
});
myscript.js //Content Script
window.onload = function () {
chrome.extension.onRequest.addListener(
function (request, sender, sendResponse) {
alert('request.JourneyDetails.FromStation');
alert(request.JourneyDetails.FromStation);
var Jour = {};
Jour.FromStation = request.FromStation;
Jour.ToStation = request.ToStation;
Jour.JourneyDate = request.JourneyDate;
chrome.storage.sync.set({ JourneyDetails: Jour }, function () {
console.log('Setting Saved')
});
//sendResponse({ counter2: "5" });
}
);
}
chrome.tabs.getSelected() is deprecated, try using chrome.tabs.query() instead? https://developer.chrome.com/extensions/tabs#method-getSelected
chrome.tabs.sendRequest() and chrome.extension.onRequest() are deprecated, try using chrome.tabs.sendMessage() and chrome.runtime.onMessage() instead? https://developer.chrome.com/extensions/tabs#method-sendRequest, https://developer.chrome.com/extensions/extension#event-onRequest
Do you include jQuery in Default_Popup.html? What are the errors you are seeing?
Are the elements with ids $('#txtFromStation'), $('#txtToStation'), $('#datepicker') in Default_Popup.html? If you could post the content of Default_Popup.html that will be helpful.

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

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() + ")()" });

Categories

Resources