I trying to code a chrome extension. Task:
On my page I have two input type=file fields. When start uploading file from one input (by choosing file from my disk and clicking upload button), I need the other file with the same name, but other folder adding to another input and start uploading too (or post it, for example).
My problem at this moment is blocking get local file by chrome extension to operate with it.
function readFile(_path, _cb){
let txt = '';
let xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if (xmlhttp.status == 200 && xmlhttp.readyState == 4){
txt = xmlhttp.responseText;
console.log(txt)
}
};
xmlhttp.open("GET", _path, true);
xmlhttp.send();
}
window.onload = function () {
document.getElementById('button').addEventListener('click', function () {
readFile('file://F:/my-file.txt', function(_res){
console.log(_res);
});
});
}
I tried to allow access by different conditions in chrome starting (such as --disable-web-security and -–allow-file-access-from-files), but it doesn't work. The answer is file:///F:/my-file.txt net::ERR_UNKNOWN_URL_SCHEME
My manifest.json:
{
"name": "Stocksy Uploader",
"version": "1.0",
"description": "Parallel upload original video files",
"permissions": ["declarativeContent","storage",{"fileSystem": ["write", "retainEntries", "directory"]},"activeTab","file:///"],
"background": {
"scripts": ["background.js"],
"persistent": false
},
"page_action": {
"default_popup": "popup.html"
},
"content_scripts": [
{
"matches": ["https://testingdomain/*"],
"js": ["contents.js"]
}
],
"manifest_version": 2
}
Related
This question already has answers here:
What is the difference between a function call and function reference?
(6 answers)
Closed 1 year ago.
So I'm trying to make an extension that allows you to write custom JS to be injected on any page for a given domain. My popup loads the saved JS code, and when clicking save, the JS is evaluated, and that works just fine. I can't figure out how to get the code to evaluate on page load, though.
Here is what I have so far.
//Content.js
//Globals
var entries = {"test": "test"}; //Entries dictionary "domain": "js code"
var url = window.location.href; //Full URL of the tab
var parts = url.split("/"); //URL split by '/' character
var domain = parts[2] + ''; //Just the domain (global)
loadChanges();
chrome.runtime.onMessage.addListener(listener);
window.onload=eval(entries[domain]); //doesn't work
function listener (request, sender, sendResponse) {
console.log("Manipulating data for: " + domain);
if (request == "LOAD"){
if(entries.hasOwnProperty(domain)){
console.log("PE - Loaded Value: " + entries[domain].toString());
sendResponse(entries[domain]);
} else {
console.log("Nothing to load");
sendResponse('');
}
} else {
entries[domain] = request;
console.log(entries[domain]);
saveChanges();
eval(request); //This one DOES work
}
}
//Load saved code (on startup)
function loadChanges() {
chrome.storage.local.get(['PE'], function (data){
console.log(data.PE);
if (data.PE == null){
return;
}
entries=data.PE;
});
if(entries.hasOwnProperty(domain)){
eval(entries[domain]); //doesn't work
}
}
//Save changes to code (on button press)
function saveChanges() {
chrome.storage.local.set({PE: entries}, function(data){
console.log("Saved Value: " + entries[domain])
});
}
Note the "doesn't work" comments in there.
manifest.json
{
"name": "PersistEdit",
"version": "0.1.1",
"manifest_version": 2,
"content_scripts":[
{
"matches": ["<all_urls>"],
"js": ["content.js"],
"run_at": "document_end",
"persistent": false
}
],
"background": {
"scripts": [
"background.js"
],
"persistent": false
},
"browser_action": {
"default_popup": "popup.html",
"default_title": "PersistEdit"
},
"permissions": [
"storage"
]
}
document.addEventListener('DOMContentLoaded', onload, false);
function onload(){
chrome.tabs.query({currentWindow: true, active: true}, function (tabs){
chrome.tabs.sendMessage(tabs[0].id, "LOAD");
});
}
Didn't include my popup.html or popup.js because those parts of it work as intended, but I can include them if necessary. I'm not sure what I'm missing here, any guidance would be appreciated.
window.onload is supposed to be a function.
Here window.onload=eval(entries[domain]); you are just assigning the result of eval to onload(which happens immediately during the assignment). It's possible that entries isn't properly populated at that time.
Try the following code
window.onload=function () {
eval(entries[domain]);
}
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
Question
I tried to make a plugin to help modify the navigator.platform, in the main page(the web browser requested page) is well, but I found that if there is a iframe in the page, iframe in the page will not be modified by my content_scripts.js, although I have to set up in the manifest.json file all_frames: true`. This is why?
manifest.json
{
"name": "Platform Modifier",
"version": "1.0.0.0",
"manifest_version":2,
"default_locale": "en",
"permissions": ["tabs", "webRequest", "webRequestBlocking", "<all_urls>"],
"background":{
"persistent":true,
"scripts":["bg.js"]
},
"browser_action": {
"default_icon": "icon.png" ,
"default_title": "Platform Modifier",
"default_popup": "popup.html"
},
"content_scripts": [{
"matches": ["*://*/*"],
"all_frames": true,
"js": ["content_scripts.js"],
"run_at":"document_start"
}],
"web_accessible_resources":[
"insert-script.js"
]
}
content_scripts.js
var xmlhttp = null;
var url = chrome.extension.getURL("insert-script.js");
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
if(xmlhttp == null){
console.log("not support XMLHTTP")
}else{
xmlhttp.onreadystatechange=state_Change;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
function state_Change(){
if(xmlhttp.status == 200){
chrome.extension.sendRequest({op: "getAll"}, function(response) {
var replaceList = {
"TAG_PlatForm":response.value.platform,
"TAG_UserAgent":response.value.userAgent
};
var sc=document.createElement("script");
sc.type="text/javascript";
sc.innerHTML= replaceText(xmlhttp.responseText,replaceList);
var html=document.getElementsByTagName("html");
html[0].appendChild(sc);
});
}
}
function replaceText(str,regexp){
for(var key in regexp){
str = str.replace(key,regexp[key]);
}
return str;
}
insert-script.js
var myPlatForm = function() {
return 'TAG_PlatForm';
};
var myUserAgent = function() {
return 'TAG_UserAgent';
};
if (Object.defineProperty) {
Object.defineProperty(navigator, 'platform', {
get: myPlatForm
});
Object.defineProperty(navigator, 'userAgent', {
get: myUserAgent
});
} else if (Object.prototype.__defineGetter__) {
navigator.__defineGetter__('platform', myPlatForm);
navigator.__defineGetter__('userAgent', myPlatForm);
}
Complete file
Download Link, this file contains two parts: extensions.zip is the Chrome extension; testPages.zip is the HTML file for testing. In the test file, open the main.html
The value is changed, just later than it is displayed in <body onload, you can check it in devtools:
The errors in the console are fixed by using the correct condition in XHR (the code was injected multiple times for each XHR loading stage, the copies tried to redefine a non-configurable property):
if (xmlhttp.readyState == 4) {
As for reducing the delay:
Currently you're waiting for XHR to fetch the injected script and waiting for the message request to the background page.
Instead put the injected script code as a literal string in your content script and use chrome.storage.local and access the values directly in the content script and the popup page.
I'm trying to make a chrome extension to modify the HTML of a page, but I can't seem to get it to work. I have four files:
manifest.json:
{
"manifest_version": 2,
"name": "Agor.aio h3cks scrubz lel",
"description": "Dis sextenzion iz wery guud",
"version": "1.0",
"background": {
"page": "test.html"
},
"content_scripts": [
{
"matches": ["http://agar.io/*"],
"js": ["contentscript.js"],
"run_at": "document_end"
}
],
"web_accessible_resources": ["script.js", "test.html"]
}
contentscript.js:
var s = document.createElement('script');
s.src = chrome.extension.getURL('script.js');
s.onload = function() {
this.parentNode.removeChild(this);
};
(document.head||document.documentElement).appendChild(s);
script.js:
$('#overlays').load('test.html');
var changeRegion = function(region) {
if(region === "Other") {
$('#changeip').toggle();
} else {
setRegion(region);
}
}
var changeIP = function(ip){
try {
connect("ws://" + ip);
} catch(err) {
console.log(err);
setRegion(document.getElementById('region').value);
}
}
var playGame = function(nick) {
setNick(nick);
setShowMass(true);
}
I don't know how to load the test.html file from within the script.js. All help is appreciated. Thank you!
You can access web-accessible resources with a url like chrome:///test.html.
If you don't know it, the id of your extensions can be found in the chrome://extensions tab. Just put it into developer mode, and the extensions id will show up under each extension. This id doesn't change, it's tied to the key you generated in your pem file.
I am writing a chrome extension, it uses chrome.windows.onFocusChanged.addListener to execute a content script. This works fine as long as I switch between different chrome windows however, the Listener is also fired when Chrome is closed. In that case the code inside the function leads to a crash of the extension.
I tried chacking for undefined, but that does not seem to be the issue.
The code lookls liks this
chrome.windows.onFocusChanged.addListener(function()
{
var ctab = chrome.tabs.getCurrent;
if(typeof ctab === "undefined")
{
}
else
{
chrome.tabs.executeScript(ctab.id,{file:"inject.js"}); //THIS LINE CRASHES THE APP WHEN I CLOSE THE BROWSER
}
});
I have a similar problem with a scheduled allert, which also executes the script (which leads to a crash when I close the browser between scheduling and execution).
function onAlarm(alarm)
{
if (alarm && alarm.name == 'check')
{
var ctab = chrome.tabs.getCurrent;
chrome.tabs.executeScript(ctab.id,{file:"inject.js"}); //CRASH
//more code...
Does anybody know how to avoid this crash?
Edit: Working Example
manifest.json
{
"name": "Rest Extension",
"description": "Set an Artnet Controler to the background collor",
"manifest_version": 2,
"version": "1",
"permissions": ["tabs", "http://*/*", "https://*/*", "background", "alarms"],
"background": {"scripts": ["background.js"]},
"content_scripts": [{"matches": ["http://*/*", "https://*/*"],"js": ["inject.js"]}],
"browser_action":
{
"default_icon": "16x16.png",
"default_popup": "popup.html"
}
}
background.js
chrome.windows.onFocusChanged.addListener(function()
{
var ctab = chrome.tabs.getCurrent;
if(typeof ctab === "undefined")
{
}
else
{
chrome.tabs.executeScript(ctab.id,{file:"inject.js"}); //THIS LINE CRASHES THE APP WHEN I CLOSE THE BROWSER
}
})
all the other files can be empty (including the inject.js)
chrome.tabs.getCurrent is a method: it's not an instance of a Tab object.
You should try this:
chrome.windows.onFocusChanged.addListener(function()
{
chrome.tabs.getCurrent(function(ctab)
{
chrome.tabs.executeScript(ctab.id, { file: "inject.js" });
});
});
Reference: http://developer.chrome.com/extensions/tabs.html#method-getCurrent