Running an extension in background on page load/refresh - javascript

I'm new to writing extensions (and javascript). I'd like an extension to run on a timer whenever a certain URL is opened/refreshed. Code is below. This is all I have so far from what I've found online. I'm not sure if this will run for just one tab at a time.
manifest.json
{
"manifest_version": 2,
"name": "Test Plugin",
"description": "This extension is a test.",
"version": "1.0",
"content_scripts": [
{
"matches": ["https://www.google.com/*"],
"js": ["main.js"]
}
],
"permissions": [
"activeTab"
]
}
main.js
chrome.tabs.onUpdated.addListener( function (tabId, changeInfo, tab) {
if (changeInfo.status == 'complete' && tab.active) {
setInterval(mainF, 5000)
}
})
function mainF() {
var getTitle = document.getElementById('title');
var titleValue = getTitle.Value();
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fh = fso.OpenTextFile("test.txt", 8, false, 0);
fh.WriteLine(titleValue);
fh.Close()
}

Move your logic to the Event Page.
Content Script doesn't have access to chrome.tabs API.
And according to best practices when using event pages,
Use event filters to restrict your event notifications to the cases you care about. For example, if you listen to the tabs.onUpdated event, try using the webNavigation.onCompleted event with filters instead (the tabs API does not support filters). That way, your event page will only be loaded for events that interest you.
Code snippets would look like
manifest.json
{
"manifest_version": 2,
"name": "Test Plugin",
"description": "This extension is a test.",
"version": "1.0",
"background": {
"scripts": ["main.js"],
"persistent": false
},
"permissions": [
"webNavigation"
]
}
main.js
chrome.webNavigation.onCompleted.addListener(function(details){
console.log("Certain url with hostSuffix google.com has been loaded");
}, {url: [{hostSuffix: 'google.com'}]});

Related

Chrome Extension, Add Listener Not Responding

I'm trying to create an alert on when chrome.tabs.audible changes condition. After reading the Google developer API information, I do not understand what I'm doing incorrectly. I'm not familiar with JS, so it is possible I'm doing something stupid...
manifest.json:
{
"name": "Extension",
"author": "Extension Author",
"description": "Extension description",
"manifest_version": 2,
"version": "1",
"permissions": [
"tabs",
],
"browser_action": {
"default_popup": "popup.html"
},
"background": {
"scripts": [
"js/background.js"
],
"persistent": false
}
}
background.js:
chrome.tabs.audible.addListener(function(tabs) {
alert("AUDIO");
});
I'm able to load the extension and load the 'popup.html' menu. If I add alert("test"); to 'backgournd.js' outside of a function, it will create the alert.
Look at the Summary table here. There is no Method, Event or Property "audible" inside it, so your chrome.tabs.audible shouldn't work. It is equal to undefined.
You should use onupdate event. So, you code looks like:
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, Tab){
if(changeInfo.audible){
console.log("The tab with id = " + tabId + "has changed its audible state.");
}
})

why Change url in Chrome tab it doesn't update tab Url when typing specify url?

I wanna make Chrome extension that when for example I typing this address:
ul/g
automatic update tab URL to:
http://ultra.com/g
this is my manifest.json:
{
"manifest_version": 2,
"name": "Test ",
"description": "Test",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.htm"
},
"background": {
"scripts": [
"src/background.js"
],
"persistent": true
},
"permissions": [
"tabs",
"activeTab",
"http://*/*",
"<all_urls>"
],
"content_scripts" : [{
"matches" : [ "http://test.com/*","<all_urls>"],
"js" : ["myScript.js"]
}]
}
and in my background.js file:
chrome.tabs.onUpdated.addListener( function( tabId, changeInfo, tab) {
if(tab.url=="ul/g"){
chrome.tabs.update(tab.Id, {url: 'http://ultra.com/g'});
}
});
why this not working?
Assuming the entire question is why this not working? an answer would be because ul/g is not an URL so Chrome redirects the text to a search engine. Here's what chrome.tabs.onUpdated sees:
{title: "ul/g - Google Search"}
{status: "loading", url: "https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=ul/g&*"}
{status: "complete"}
You can intercept omnibox search requests using webRequest API. For example with google search by default you can see requests like this:
https://www.google.com/complete/search?client=chrome-omni&..............&q=ul%2Fg..............
So check if the URL has &q= parameter that matches e.g. \w+%2Fg and abort it using a blocking onBeforeRequest listener, then update the tab URL to http://ultra.com/g. You can find examples here on StackOverflow and in the documentation.

Catching YouTube video going fullscreen in extension

As starter in Chrome extensions i'm trying to triger my function when somebody puts his youtube video into fullscreen. I've came up with code below, but it still don't triggers the alert message.
Manifest.json
{
"name": "Ext",
"version": "0.1",
"manifest_version": 2,
"description": "Catching fullscreen.",
"icons": {"16": "icon_16.png"
},
"background": {
"scripts": ["background.js"]
},
"browser_action":{
"default_title": "Ext",
"default_icon": "icon_16.png"
},
"permissions": [
"background",
"tabs",
"http://*/*",
"https://*/*"
]
}
background.js
document.addEventListener('DOMContentLoaded', function() {
var link = document.getElementByClassName('ytp-fullscreen-button');
link.addEventListener('click', function() {
alert("Fullscreen");
});
});
Beside answering to question how to add custom listener to video going fullscreen event i would be very thankful for some tips how to improve myself in this type of apps.
Read the extensions architecture overview: background page of an extension is not related to the web page so the background page script doesn't have direct access to webpage document or events.
Use a content script and fullscreenchange event (currently, it's under a vendor prefix):
addVendorEventListener(document, 'fullscreenchange', onFullscreenChange);
function onFullscreenChange(event) {
console.log(event);
}
function addVendorEventListener(element, eventName, callback) {
var vendorName = 'on' + eventName in element ? eventName
: 'onwebkit' + eventName in element ? 'webkit' + eventName
: 'onmoz' + eventName in element ? 'moz' + eventName
: null;
if (vendorName)
element.addEventListener(vendorName, callback);
}
manifest.json:
"content_scripts": [{
"matches": ["https://www.youtube.com/*"],
"js": ["content.js"]
}],

Injecting content script for Chrome extension isn't working

I've researched this topic a ton but something isn't clicking. I'm trying to make a simple Chrome extension. The details aren't important, but basically when the user clicks on a certain button on a certain website, the page is redirected to a different URL. I've put in dummy URLs just for illustration. Here is my code:
manifest.json
{
"manifest_version": 2,
"name": "Blah",
"version": "1.0",
"description": "Blah blah",
"icons": { "16": "icon16.png",
"48": "icon48.png",
"128": "icon128.png" },
"content_scripts": [
{
"matches": ["*://url1.com/*"],
"js": ["contentscript.js"]
}
],
"web_accessible_resources": ["script.js"]
}
contentscript.js (found this on another Stack Overflow question, not totally sure how it works)
var s = document.createElement("script");
s.src = chrome.extension.getURL("script.js");
s.onload = function() {
this.remove();
};
(document.head || document.documentElement).appendChild(s);
script.js
document.getElementById("id1").addEventListener("click", redirect);
function redirect() {
console.log("Testing!"); // This works!
window.location.replace("url2.org");
}
The text is logged to the console when I click the appropriate button, so I know I'm doing something right. However, I'm guessing I'm not actually injecting the script into the page, and that's why my page isn't redirecting. Any help would be appreciated!
Here is an example:
script.js
// wait that page finished loading
window.addEventListener("load", function load(event){
// for the current tab, inject the "inject.js" file & execute it
chrome.tabs.executeScript(tab.ib, {
file: 'inject.js'
});
},false);
inject.js
// this is the code which will be injected into a given page...
document.getElementById("id1").addEventListener("click", redirect);
function redirect() {
console.log("Testing!"); // This works!
window.location.replace("url2.org");
}
Manifest.json
{
"name": "Inject",
"version": "0.0.1",
"manifest_version": 2,
"description": "Injecting stuff",
"content_scripts": [{
"matches": ["http://example.com/*"],
"js": ["script.js"]
}],
"permissions": [
"http://example.com/*",
"tabs"
]
}

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

Categories