Chrome Extension Background Function - javascript

I'm trying to define a background function and use it in popup.js. Because, I want to send POST request and don't know a way to do it in popup.js. I've searched for it and so many people just say, it's better to send a POST request in background.js. And chrome blocks the request from popup.js.
Here is my manifest.json:
{
"name": "Getting Started Example",
"version": "1.0",
"description": "Build an Extension!",
"permissions": [
"declarativeContent",
"activeTab",
"tabs",
"storage",
"webNavigation",
"<all_urls>"
],
"background_page": "background.html",
"background": {
"scripts": ["background.js"],
"persistent": false
},
"page_action": {
"default_popup": "popup.html",
"default_icon": {
"16": "icon-16.png",
"48": "icon-48.png",
"128": "icon-128.png"
}
},
"icons": {
"16": "icon-16.png",
"48": "icon-48.png",
"128": "icon-128.png"
},
"manifest_version": 2
}
How can I do it?

Have a look at my code, I have build one password manager extension which interact server and get password to fill in form and it works like a charm. below is the manifest of this app.
{
"name": "Password Manager",
"version": "0.3",
"description": "Manage all Passwords",
"options_page": "options.html",
"permissions": [
"contentSettings",
"tabs",
"activeTab",
"http://*/",
"storage",
"webRequest",
"webRequestBlocking",
"debugger",
"<all_urls>",
{"fileSystem": ["write", "retainEntries", "directory"]}
],
"browser_action": {
"default_icon": "images/icon.png",
"default_popup": "app.html"
},
"manifest_version": 2,
"content_scripts": [
{
"matches": [
"*://*/*"
],
"js": [
"scripts/jquery.js"
]
}],
"background": {
"scripts": [
"scripts/jquery.js",
"scripts/custom.js"
],
"persistent": true
}
}
if you have a look at app.html code below I am able to execute the code in popup.js
<!DOCTYPE html>
<html>
<head>
<title>Popup</title>
<link href="css/bootstrap.css" rel="stylesheet" />
<link href="css/style.min.css" rel="stylesheet" />
<style>
body {
margin: 20p;
padding: 20px;
width: 300px;
min-height: 150px;
}
.header{
width: 100%;
position: absolute;
top: 20px;
}
</style>
</head>
<body>
<br/>
<div class='header'>
User: <label id="username" ></label>
<br/><button class='btn btn-xs btn-warning options_helper' >Settings</button>
</div>
<br/><hr/>
<div id="jstree_demo_div">
</div>
</body>
<script src="scripts/jquery.js"></script>
<script src="scripts/bootstrap.js"></script>
<script src="scripts/jstree.min.js"></script>
<script src="scripts/popup.js"></script>
<script src="scripts/components/core.js"></script>
<script src="scripts/components/lib-typedarrays.js"></script>
<script src="scripts/components/x64-core.js"></script>
<script src="scripts/components/enc-utf16.js"></script>
<script src="scripts/components/enc-base64.js"></script>
<script src="scripts/components/md5.js"></script>
<script src="scripts/components/sha1.js"></script>
<script src="scripts/components/sha256.js"></script>
<script src="scripts/components/sha224.js"></script>
<script src="scripts/components/sha512.js"></script>
<script src="scripts/components/sha384.js"></script>
<script src="scripts/components/ripemd160.js"></script>
<script src="scripts/components/hmac.js"></script>
<script src="scripts/components/pbkdf2.js"></script>
<script src="scripts/components/evpkdf.js"></script>
<script src="scripts/components/cipher-core.js"></script>
<script src="scripts/components/mode-cfb.js"></script>
<script src="scripts/components/mode-ctr.js"></script>
<script src="scripts/components/mode-ofb.js"></script>
<script src="scripts/components/mode-ecb.js"></script>
<script src="scripts/components/pad-ansix923.js"></script>
<script src="scripts/components/pad-iso10126.js"></script>
<script src="scripts/components/pad-zeropadding.js"></script>
<script src="scripts/components/pad-iso97971.js"></script>
<script src="scripts/components/pad-nopadding.js"></script>
<script src="scripts/components/rc4.js"></script>
<script src="scripts/components/rabbit.js"></script>
<script src="scripts/components/aes.js"></script>
<script src="scripts/components/tripledes.js"></script>
<script src="scripts/crypt.js" type="text/javascript"></script>
</html>
and final part for you as you can see I am using ajax in popup.js to retrieve passwords file to save it locally from server.
// document.addEventListener("contextmenu", function(e) {
// e.preventDefault();
// });
var key = localStorage.getItem("access_key");
$(document).ready(function(){
readTextFile("file://"+localStorage.getItem("db_path"));
var menuItems="";
var key = '';
});
$('#jstree_demo_div').on("select_node.jstree", function (e, data) {
chrome.tabs.query({ currentWindow: true, active: true },function (tabArray) {
chrome.tabs.executeScript(tabArray[0].id, {
file: 'scripts/pop.js'
}, function() {
chrome.tabs.sendMessage(tabArray[0].id,{type: data.node.data.jstree.type, options: {
user: data.node.data.jstree.user,
pass: data.node.data.jstree.pass
}
})
})
}
);
});
$(".options_helper").click(function(){
chrome.tabs.create({ url: "options.html" });
})
function readTextFile(file)
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var fullresponse = decrypt(rawFile.responseText,key);
var username = fullresponse.split("|")[1];
var userdata = fullresponse.split("|")[0];
$("#username").text(username);
if (decrypt(rawFile.responseText,key).length>0){
$('#jstree_demo_div').html(userdata);
$('#jstree_demo_div').jstree();
}else{
$('#jstree_demo_div').html("Password Database is not found");
}
}else{
$('#jstree_demo_div').html("Password Database is not found");
}
}else{
}
}
rawFile.send(null);
}
Hope I am able to help you with my whole program written. In case you have question for any part of it. do let me know.

Related

Youtube Playback Chrome Extension

I cannot understand why this isn't working.
I have checked the google extension dev docs, checked some sample code.
Checked other stackoverflow Question/Answers without any positive feedback/results from testing.
This extension is very simple
It displays a popup with an input text field and a button
on clicking it will send a message to the content script via postMessage to update the document.getElementsByTagName("video")[0].playbackRate
this will adjust youtubes or other supported (future venture) Video
Playback Speed beyond or lower than the default of 0.25, 0.50, 1, 1.25, 1.50, 2 or to an exact value like 1.4390
Easier and faster than using said console + devtools, etc..which speeds up the initial setup...
please help :)
manifest.json
{
"manifest_version": 2,
"name": "Youtube Playback",
"version": "1.0",
"description": "Manage Playback Speed With Any Value",
"homepage_url": "https://github.com/DeanVanGreunen",
"permissions": [
"tabs",
"activeTab"
],
"browser_action": {
"icon": "icon.png",
"default_icon": "icon.png",
"title": "Youtube Playback",
"default_title": "Youtube Playback",
"popup": "popup.html",
"default_popup": "popup.html"
},
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": ["content.js"]
}
]
}
popup.html
<script>
function setPlaybackSpeed(speed){
chrome.tabs.query({currentWindow: true, active: true}, function (tabs){
var activeTab = tabs[0];
chrome.tabs.sendMessage(activeTab.id, {action: "setPlaybackSpeed", "speed": speed});
});
}
</script>
<div>
<input id="text_playbackspeed" type="text" style="" placeholder="1" value="1"/>
<button id="btn_updateplaybackspeed" style="">Update</button>
</div>
content.js
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if( request.action === "setPlaybackSpeed" ) {
document.getElementsByTagName("video")[0].playbackRate = request.playback_speed;
}
return true;
}
);
Here is the working solution (its being a while however here you go, I forgot to update this thread)
Overview
This extension is very simple
It displays a popup with an input text field and a button
on clicking it will send a message to the content script
via postMessage to update the document.getElementsByTagName("video")[0].playbackRate
this will adjust youtubes or other supported (future venture) Video Playback
Speed beyond or lower than the default of 0.25, 0.50, 1, 1.25, 1.50, 2 or up a max of 4 times the original speed by using 4
an exact value like 1.4390
Easier and faster than using said console + devtools, etc..which speeds up the initial setup...
Project Repo Hosted on Github at:
https://github.com/DeanVanGreunen/YT_SpeedMeUpExtension
Or get the latest release via:
https://github.com/DeanVanGreunen/YT_SpeedMeUpExtension/releases/
Or see latest updated Files below:
manifest.json
{
"manifest_version": 2,
"name": "Youtube Playback",
"version": "1.0",
"description": "Manage Playback Speed With Any Value",
"homepage_url": "https://keybase.io/DeanVanGreunen",
"repo_url": "https://github.com/DeanVanGreunen/YT_SpeedMeUpExtension",
"permissions": [
"tabs",
"activeTab"
],
"icons": {
"128": "icon.png"
},
"browser_action": {
"default_icon": {
"128": "icon.png"
},
"default_title": "Youtube Playback",
"default_popup": "popup.html"
},
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": ["content.js"]
}
]
}
popup.html
<style>
#text_playbackspeed {
padding: 2px;
margin-bottom: 4px;
}
#leButtons, #findsMe {
padding: 4px 8px;
text-align: center;
margin:0px auto;
}
#findsMe img{
display: block;
margin: 0 auto;
width: 69px;
height: 69px;
}
</style>
<div>
<input id="text_playbackspeed" type="text" style="" placeholder="1" value="1"/>
<div id="leButtons">
<button id="btn_updateplaybackspeed_minus" style="">-1</button>
<button id="btn_updateplaybackspeed" style="">Update</button>
<button id="btn_updateplaybackspeed_add" style="">+1</button>
</div>
</div>
<div id="findsMe">
<img src="https://avatars0.githubusercontent.com/u/22296075" alt="The Developer" />
<a target="_blank" href="https://keybase.io/DeanVanGreunen">Find me</a>
</div>
<script type="text/javascript" src="popup.js"></script>
popup.js
function setPlaybackSpeed(speed){
chrome.tabs.query({currentWindow: true, active: true}, function (tabs){
var activeTab = tabs[0];
chrome.tabs.sendMessage(activeTab.id, {action: "setPlaybackSpeed", "speed": speed});
});
}
function getPlaybackSpeed(){
chrome.tabs.query({currentWindow: true, active: true}, function (tabs){
var activeTab = tabs[0];
chrome.tabs.sendMessage(activeTab.id, {action: "getPlaybackSpeed"});
});
}
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if(sender.tab){
if( request.action == "returnPlaybackSpeed" ) {
document.getElementById('text_playbackspeed').value = request.speed;
}
}
}
);
document.getElementById('btn_updateplaybackspeed_minus').addEventListener('click', function(event) {
var num = parseFloat(document.getElementById('text_playbackspeed').value)-1;
document.getElementById('text_playbackspeed').value = num;
});
document.getElementById('btn_updateplaybackspeed_add').addEventListener('click', function(event) {
var num = parseFloat(document.getElementById('text_playbackspeed').value)+1;
document.getElementById('text_playbackspeed').value = num;
});
document.getElementById('btn_updateplaybackspeed').addEventListener('click', function(event) {
setPlaybackSpeed(document.getElementById('text_playbackspeed').value);
});
getPlaybackSpeed();
content.js
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if(!sender.tab){
if( request.action == "getPlaybackSpeed" ) {
chrome.runtime.sendMessage({action: "returnPlaybackSpeed", speed: document.getElementsByTagName("video")[0].playbackRate}, function(){});
} else if( request.action == "setPlaybackSpeed" ) {
document.getElementsByTagName("video")[0].playbackRate = request.speed;
}
}
}
);
icon.png

chrome extension for selecting a text and sending it for google search?

I am trying to develop a simple chrome extension in which i want to select a text from any web page and after clicking on a button it must search text in google.
I am new to extension. Right now i am able to select the text. But i can not able to google it. My code is as below.
Manifest.json
{
"name": "Selected Text",
"version": "0.1",
"description": "Selected Text",
"manifest_version": 2,
"browser_action": {
"default_title": "Selected Text",
"default_icon": "icon.PNG",
"default_popup": "popup.html"
},
"permissions": [
"tabs",
"<all_urls>"
],
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["popup.js"]
}
]
}
popup.html
<!DOCTYPE html>
<html>
<head>
<script src="popup.js"></script>
<style>
body { width: 300px; }
textarea { width: 250px; height: 100px;}
</style>
</head>
<body>
<textarea id="text"> </textarea>
<button id="Hindi" button onclick="Hindi Meaning">Hindi Meaning</button>
</body>
</html>
popup.js
chrome.tabs.executeScript( {
code: "window.getSelection().toString();"
}, function(selection) {
console.log(selection[0]);
if(selection[0].length > 0){
document.getElementById("text").value = selection[0];
}
});
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.sendRequest(tab.id, {method: "getSelection"}, function(response) {
var selectedText = document.getElementById("text").value = selection[0];
chrome.tabs.create({url: 'http://google.com?q=' + selectedText});
});
});

Google Chrome Extension Getting Selected Text Sometimes Empty?

I'm developing little chrome extension.
I could not figured it out how getSelection works in chrome extension.
Sometimes selected text comes loaded , sometimes it is empty. why?!
Here is my manifest file:
{
"background": {
"scripts": [
"js/pop.js"
]
},
"browser_action": {
"default_icon": "icons/icon.png",
"default_popup": "popup.html"
},
"content_scripts": [
{
"js": [
"js/contentscript.js",
"js/lib/jquery-2.1.4.min.js",
"js/lib/hi5.js"
],
"matches": [
"http://*/*",
"https://*/*",
"file://*",
"<all_urls>"
],
"run_at": "document_end",
"all_frames": true
}
],
"icons": {
"16": "icons/icon16.png",
"24": "icons/icon24.png",
"32": "icons/icon32.png",
"48": "icons/icon48.png",
"64": "icons/icon64.png",
"96": "icons/icon96.png",
"128": "icons/icon128.png"
},
"commands": {
"_execute_browser_action": {
"suggested_key": {
"chromeos": "Alt+D"
}
}
},
"name": "App",
"manifest_version": 2,
"permissions": [
"tabs",
"contentSettings",
"management",
"contextMenus",
"http://*/",
"https://*/",
"<all_urls>",
"storage",
"unlimitedStorage"
],
"update_url": "https://clients2.google.com/service/update2/crx",
"version": "1.0",
"web_accessible_resources": [
"js/lib/jquery-2.1.4.min.js"
]
}
Here is my contentscript:
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
if (request.method == "getSelection") {
var selectedText = window.getSelection().toString();
sendResponse({data: selectedText});
}
}
);
Here is my pop.js:
document.addEventListener('DOMContentLoaded', function () {
chrome.tabs.query({active: true, windowId: chrome.windows.WINDOW_ID_CURRENT},
function (tab) {
chrome.tabs.sendMessage(tab[0].id, {method: "getSelection"},
function (response) {
var selectedTex = response.data;
if (selectedTex.length > 1) {
$("#search-basic").val(selectedTex);
}
});
});
});
Here is my popUp.html
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery Mobile: Theme Download</title>
<link rel="stylesheet" href="themes/deneme.min.css"/>
<link rel="stylesheet" href="themes/jquery.mobile.icons.min.css"/>
<link rel="stylesheet" href="./css/jquery.mobile-1.4.5.min.css"/>
<script type="text/javascript" src="./js/lib/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="./js/lib/jquery.mobile-1.4.5.min.js"></script>
<script type="text/javascript" src="./js/pop.js"></script>
</head>
<body>
<input type="search" name="search" id="search-basic" value=""/>
</body>
</html>
I assume your problem is the way you use to get the selected text.
Instead to use:
var selectedText = window.getSelection().toString();
try this other code:
var focused = document.activeElement;
var selectedText;
if (focused) {
try {
selectedText = focused.value.substring(
focused.selectionStart, focused.selectionEnd);
} catch (err) {
}
}
if (selectedText == undefined) {
var sel = window.getSelection();
selectedText = sel.toString();
}

chrome.tabs.onCreated and executescript for Chrome Extensions not working

I'm trying to execute some script inside another external page off of a new tab listener.
background.js
function onCreatedChrome(){
chrome.tabs.onCreated.addListener(function(tab) {
if (tab.url.indexOf("chrome-devtools://") == -1) {
localStorage.setItem("tabid", tab.id);
chrome.tabs.executeScript(tab.id, {code: "alert('Hello World')"}, function() {
if (chrome.runtime.lastError) {
localStorage.setItem("Error", chrome.runtime.lastError.message);
console.error(chrome.runtime.lastError.message);
}
else{
localStorage.setItem("Else case", "This should work")
}
});
}
});
}
function createTab(){
return function(){
var url = "https://www.yahoo.com/";
chrome.tabs.create({ url: url });
}
}
$(document).ready(function(){
onCreatedChrome();
$("#button").click(createTab());
});
manifest.json
{
"manifest_version": 2,
"name": "Execute Script",
"description": "ExecuteScript extension",
"version": "1.0",
"permissions": [
"activeTab",
"tabs",
"http://*/*",
"https://www.yahoo.com/*"
],
"content_scripts": [
{
"matches": ["https://*/*"],
"js": ["jquery.js"]
}
],
"background":{
"scripts": ["background.js",
"jquery.js"]
},
"browser_action": {
"default_popup": "index.html"
}
}
index.html
<html>
<head></head>
<body>
<button id="button">Click Me</button>
</body>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="background.js"></script>
</html>
I want thealert('Hello World')to be injected into Yahoo!'s homepage (This is just an example of what I am trying to do in another extension)
The problem with your code is becuase you added jQuery.js after the background.js file
Here is the fix:
"background":{
"scripts": ["jquery.js",
"background.js"]
},
Another alternative for the executeScrit task:
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if (changeInfo.status != 'complete')
return;
if (tab.url.indexOf('yahoo.com') != -1) {
chrome.tabs.executeScript(tabId, {
code: 'alert(1)'
});
}
});

javascript flashcard

Can someone please tell me why the following extension does not work? I tried to replace the inline script with script src=" ..." /script and it still doesn't work. Is it better to list both javascripts in content scripts or remove them both?
POPUP.html
<!DOCTYPE html>
<html>
<head>
<style>
body { width: 300px; }
textarea { width: 250px; height: 100px;}
</style>
<script>
function pasteSelection() {
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.sendRequest(tab.id, {method: "getSelection"}, function (response) {
var text = document.getElementById('text');
text.innerHTML = response.data;
});
});
}
</script>
</head>
<body>
<textarea id="text"> </textarea>
<button onclick="pasteSelection(); ">Paste Selection</button>
</body>
</html>
selection.js
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if (request.method == "getSelection")
sendResponse({data: window.getSelection().toString()});
else
sendResponse({}); // snub them.
});
manifest.json
{
"name": "Selected Text",
"version": "0.1",
"description": "Selected Text",
"browser_action": {
"default_title": "Selected Text",
"default_icon": "online.png",
"default_popup": "popup.html"
},
"permissions": [
"tabs",
"chrome://favicon/",
"http://*/*",
"https://*/*"
],
"content_scripts": [
{
"matches": ["http://*/*"],
"js": ["selection.js", "paste.js"]
"run_at": "document_start",
"all_frames": true
}
]
}
You can't use any inline code and you are using several depreciated methods. Not moving all of the inline code to an external file is probably what is causing the problem, but it is not good to use depreciated methods anyway. Fixing it would make it look like this:
Popup.html
<!DOCTYPE html>
<html>
<head>
<style>
body { width: 300px; }
textarea { width: 250px; height: 100px;}
</style>
<script src="popup.js"></script>
</head>
<body>
<textarea id="text"> </textarea>
<button id="pasteButton">Paste Selection</button>
</body>
</html>
Popup.js
window.onload = function() {
var pasteButton = document.getElementById("pasteButton");
pasteButton.onclick = function(){
chrome.tabs.query({active:true,currentWindow:true}, function(tab) {
chrome.tabs.sendMessage(tab[0].id,{method:"getSelection"},function(response){
var text = document.getElementById('text');
text.innerHTML = response.data;
});
});
};
};
selection.js
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
if (request.method == "getSelection")
sendResponse({data: window.getSelection().toString()});
else
sendResponse({}); // snub them.
});
Manifest.json
{
"name": "Selected Text",
"version": "0.1",
"description": "Selected Text",
"manifest_version": 2,
"browser_action": {
"default_title": "Selected Text",
"default_icon": "online.png",
"default_popup": "popup.html"
},
"permissions": [
"tabs",
"chrome://favicon/",
"http://*/*",
"https://*/*"
],
"content_scripts": [{
"matches": ["http://*/*"],
"js": ["selection.js", "paste.js"],
"run_at": "document_start",
"all_frames": true
}]
}

Categories

Resources