undefined URL in chrome extension - javascript

I'm making a simple extension that gets URL of the current tab and saves it to the storage when I click a 'create' button and retrieve URL when 'goto' button clicked.
I got undefined tab and url debugging this code. I'm new to chrome extension and javascript and would appreciate your help! :)))
this is my popup.js
$(function() {
$('#create').click(function() {
var tab;
var myUrl;
chrome.tabs.query({active: true, lastFocusedWindow: true}, function(tabs){
tab = tabs[0];
myUrl = tab.url;
});
chrome.storage.sync.set({'newUrl': myUrl});
});
});
popup.html
<script src= "jquery-3.4.1.min"></script>
<script src = "popup.js"></script>;
</head>
<body>
<input type = "button" id = "create" value = "create">
<input type = "button" id = "go" value = "go to">
</body>
manifest.json
"permissions": [
"tabs",
"activeTab",
"bookmarks",
"contextMenus",
"storage",
"*://*/*"
],

chrome.* apis can be accessed from background and popup scripts only.
You have written those chrome.* api in injectedScript or content script.

Related

Need Help Display DOM Content For Google Chrome Extension

I am creating a Google Chrome Extension that uses a script that works perfectly well in Google Chrome's console.
However, I am trying to use this same script beyond just printing the information in console.
How would I be able to somehow create HTML elements that contain this information within the popup.html page? I know that this idea might have to use the callback function within
Here is my code:
manifest.json
{
"manifest_version": 2,
"name": "MR QC Auditor View",
"version": "1.0",
"description": "This Google Chrome extension shows Ad ID's for print ads, and then links to Ad Tagger for tagging corrections",
"icons": {
"128": "MRLogo128.png",
"48": "MRLogo48.png",
"16": "MRLogo16.png"
},
"browser_action":{
"default_icon": "MRLogo16.png",
"default_popup": "popup.html"
},
"permissions": [
"storage",
"tabs",
"activeTab"
]}
popup.html:
<!DOCTYPE html>
<html>
<head>
<title>MR QC Auditor View</title>
<script src="jquery-3.3.1.min.js">
</script>
<script src="popup.js">
</script>
</head>
<body>
<img src="MRLogo128.png"/>
<h1>Current Ad's Brand: <h1><span id="brandNameText"></span>
<h2>Link To Ad Tagger</h2><span>Link</span>
</body>
</html>
popup.js:
// Current Post To Look At:
// https://stackoverflow.com/questions/4532236/how-to-access-the-webpage-dom-rather-than-the-extension-page-dom
// Related Google + Group Post:
// https://groups.google.com/a/chromium.org/forum/#!topic/chromium-extensions/9Sue8JRwF_k
// Use chrome.runtime.onMessage()
// Documentation:
// https://stackoverflow.com/questions/3010840/loop-through-an-array-in-javascript
// chrome.tabs.executeScript():
// https://developer.chrome.com/extensions/tabs#method-executeScript
/*
Old Code Block;
chrome.tabs.executeScript({file: 'jquery-3.3.1.min.js'}, function () { chrome.tabs.executeScript({code: 'var printAds = document.getElementsByClassName("ad-image printadviewable pointer"); ', allFrames: true}, function(stuff){
chrome.runtime.sendMessage({greeting: "hello"}, function(){
// Call chrome.runtime.sendResponse()
// console.log("DOM Content Sent To Chrome Extension Webpage");
})
}}); });
*/
// Added an array called "adArray" that utilizes the .push() JavaScript array function
// I need to somehow add this to the popup.html page itself, look for the StackOverflow related pages.
chrome.tabs.executeScript({file: 'jquery-3.3.1.min.js'}, function (adArray) { chrome.tabs.executeScript({code: 'var printAds = document.getElementsByClassName("ad-image printadviewable pointer"); var adArray = []; for (var i = 0; i<printAds.length; i++){console.log("Current Ad Id = " + $(printAds[i]).attr("data-adid")); adArray.push($(printAds[i]).attr("data-adid"))}', allFrames: true}); });
/*
Console Based Code That Works:
$("#ad-image printadviewable pointer").find("img").attr("data-adid");
var printAds = document.getElementsByClassName("ad-image printadviewable pointer");
for (var i = 0; i<printAds.length; i++){console.log("Current Ad Id = " + $(printAds[i]).attr("data-adid"));}
*/
// One Line Version For Code Dictionary Key
// 'var printAds = document.getElementsByClassName("ad-image printadviewable pointer"); for (var i = 0; i<printAds.length; i++){console.log("Current Ad Id = " + $(printAds[i]).attr("data-adid"));}'

Load a javascript file when i select an option in popup.html

im making a chrome extension and i have a problem loading a file...
I want to load a file when i select an option in the popup.html file
for example, if i select option1 i want eventPage1.js, to be loaded, and if i select option2 i want eventPage2.js to be loaded, but not the two at the same time, just one.
This its my popup.html file
<!DOCTYPE html>
<html>
<form>
Paises en el menu contextual:
<br>
<div>
<input type="radio" id="opcion1" name="opcion" value="opcion1" onclick= <script src="eventPage1.js"></script>
<label for="opcion1">Todos los paises</label>
<input type="radio" id="opcion2" name="opcion" value="opcion2" onclick= <script src="eventPage2.js"></script>
<label for="opcion2">Solo Mexico</label>
</div>
</form>
</body>
</html>
each eventpage file, its a context menu...
this its how my manifest file looks like
{
"manifest_version": 2,
"name": "help me",
"author": "me man",
"version": "1.1.4",
"description": "test test",
"browser_action":
{
"default_icon": "icon-large.png",
"default_popup": "popup.html"
},
"background": {
"scripts": ["menuSelection.js"]
},
"permissions": [
"storage",
"contextMenus"
],
"icons": {
"16": "icon-bitty.png",
"48": "icon-small.png",
"128": "icon-large.png"
}
}
another problem that i have, its that when i select an option... save that option in storage so everytime i use the extension its automatically loaded that option
Event page is a technical term for the page declared in "background" section of manifest.json with "persistent": false. It's not just a name. It's a special context which exists only for that single hidden page. Make sure to read the extension architecture overview.
Inline code in html file doesn't work in extension pages by default for security reasons (the onclick attribute in your html). Handle all events in a separate js file
The input tags in your html aren't closed, and actually malformed. There's no opening <body>.
To save the options use chrome.storage API or the old primitive string-based localStorage
To dynamically load js files, add a script element dynamically into head with its src property set to the name of the file to load. Or use the modern require()-based approach. However, you might want to start learning using a single script file.
Don't use form: the browser is not a web server so the page cannot be submitted. It will simply reload and you'll lose all data. Of course you can prevent the submit event in a listener but it defeats the purpose of using a form. Instead process a change immediately.
popup.html:
<!DOCTYPE html>
<html>
<body>
Paises en el menu contextual:
<div>
<label><input type="radio" name="opcion" value="opcion1">Todos los paises</label>
<label><input type="radio" name="opcion" value="opcion2">Solo Mexico</label>
</div>
<script src="popup.js"></script>
</body>
</html>
popup.js:
function setRadio(name, value) {
const el = document.querySelector(`input[name="${name}"][value="${value}"]`);
if (el && !el.checked) {
el.checked = true;
}
}
chrome.storage.sync.get('opcion', data => {
setRadio('opcion', data.opcion);
});
document.onchange = event => {
if (event.target.name == 'opcion') {
const value = event.target.value;
chrome.storage.sync.set({opcion: value});
switch (value) {
case 'opcion1':
doSomething1();
break;
case 'opcion2':
doSomething2();
break;
}
}
};
chrome.storage.onChanged.addListener((changes, area) => {
if (area == 'sync' && 'opcion' in changes) {
setRadio('opcion', changes.opcion.newValue);
}
});
I think you would probably want to do something like this when you click on the selected option:
<script type="text/javascript">
function LoadJavascriptFile(fileToLoad){
var script = document.createElement("script");
script.id = "customScript";
script.type = "text/javascript";
script.src = "fileToLoad";
document.getElementsByTagName("head")[0].appendChild(script);
}
</script>
On you option select you'd call
LoadJavascriptFile("PathToMyFile.js")
You'd then check if the Script ID exists in the header. If it does, update the SRC otherwise create the SRC

Display Date and save it into a text file using Chrome Extension [duplicate]

This question already has answers here:
The Chrome extension popup is not working, click events are not handled
(2 answers)
How to fix chrome-extension inline JavaScript invocation error?
(3 answers)
Closed 5 years ago.
I am creating an extension that tracks the specific url and displays the date when that url is accessed then saves it into a text file. It works when I just run the page and script but when adding it to chrome it does nothing.
Manifest.json
{
"name": "Login Tracker",
"version": "0.1",
"manifest_version": 2,
"description": "A Chrome Extension that records the time that you log in",
"browser_action": {
"default_icon": "icon.png",
"default_title": "Login Tracker"
},
"permissions": ["tabs",
"background", "browsingData", "contextMenus", "downloads"
],
"background": {
"scripts": ["loginPage.js", "func.js"]
}
}
loginPage.html
<html>
<head>
<script type="text/javascript" src="func.js">
</script>
</head>
<body>
<h1>Login Tracker</h1>
<p id=demo></p>
<button type="button" onclick="myFunction()">Login</button>
</body>
</html>
func.js
function myFunction() {
var d = new Date();
document.getElementById("demo").innerHTML = d;
var textToSave = d;
var hiddenElement = document.createElement('a');
hiddenElement.href = 'data:attachment/text,' +
encodeURI(textToSave);
hiddenElement.target = '_blank';
hiddenElement.download = d;
hiddenElement.click();
}
loginPage.js
chrome.browserAction.onClicked.addListener(function (activeTab) {
var newURL = "loginPage.html";
chrome.tabs.create({
url: newURL
});
});
Any idea why it does not do anything even just displaying the date? Its working when I view it in local but it does not do anything when being added to chrome. Any help will be appreciated.

Simple chrome extension URL to send/show

I am trying to do something simple and somehow it does not work...
I am trying to build a simple chrome extension that when you click on it it is showing the URL of the TAB in a simple HTML. How can I do it? this is the code:
manifest.json
{
"name": "MY EXTENSION",
"version": "1.0",
"description": "the DESCRIPTION",
"browser_action": {
"default_icon": "icon.png",
"popup": "main.html"
},
"permissions": [
"tabs"
]
}
End of manifest.json
Main.html:
<html>
<head>
<title>my title</title>
<script src="jquery.json-2.3.min.js"></script>
<script type="text/javascript">
var pageUrl = null;
var pageTitle = null;
var Title1 = 'lala';
window.addEventListener("load", windowLoaded, false);
function windowLoaded() {
chrome.tabs.getSelected(null, function(tab) {
document.getElementById('currentLink').innerHTML = tab.url;
});
}
function get(){
chrome.tabs.getSelected(null, function(tab) {
pageUrl = tab.url;
pageTitle = tab.title;
$('#bkmk').attr('value',pageUrl);
$('#title').attr('value',pageTitle);
});
}
</script>
</head>
<body onload="get()">
<p id="currentLink">Loading ...</p>
<hr />
<ul id="savedLinks"></ul>
<tr><td align="right">Link (URL): </td><td><input id='bkmk' name='bkmk' type="text" value="" size="50">
<br><span style="color: red;"></span>
</td></tr>
<script>document.write($bkmk)</script>
</body>
</html>
=============
and I placed the jquery.json-2.3.min.js file in the same folder..
Anything I do I cannot make the HTML to show the URL..
Thanks!!
Elikd
It appers that you are using jQuery... but you don't have the jQuery library included in a <script src="..."></script> block anywhere. If you're using a local copy of jQuery, you need to include the jQuery library file in your extension directory and refer to its relative path in the extension relative to the HTML page (e.g., "jquery.min.js" if it's in the same folder or "lib/jquery.min.js" if it's in a folder called lib).
In the future, you can get a JavaScript console (with a list of errors) by right-clicking your browser action icon and selecting "Inspect popup". See Google's tutorial on debugging Chrome extensions for more information.

Chrome Extension - javascript in onClick function only works when debugging

I am creating a Chrome Extension that upon clicking the extension icon will present the user with a button, clicking that button will open a new tab which will display a parameter passed to it from the original page. The strange thing is that this will work if I debug it (i.e. right click the extension icon and click "Inspect popup"), but it will just show a blank page upon clicking the button if I'm not debugging.
manifest.json
{
"name": "test name",
"version" : "0.1",
"description": "test description",
"browser_action":
{
"default_icon": "icon_128.png",
"popup": "test.html"
},
"permissions": [
"tabs", "http://*/*", "https://*/*"
]
}
test.html
<HTML>
<BODY>
<script type="text/javascript">
var currentWindowID = -1;
window.onload = function(e){
chrome.windows.getCurrent(function(w)
{
currentWindowID = w.id;
});
}
function openNextPage(){
console.log("in openNextPage");
chrome.tabs.create(
{url: "test2.html"},
function(tab)
{
chrome.tabs.sendRequest(tab.id, {someParam: currentWindowID});
}
);
console.log("exiting openNextPage");
}
</script>
<input type="button" value="Show next page" onClick="openNextPage()">
</BODY>
</HTML>
test2.html
<HTML>
<script type="text/javascript">
chrome.extension.onRequest.addListener(function(request)
{
document.write("<h1>test</h1>");
document.write("<h2>value=" + request.someParam + "</h2>");
});
</script>
</HTML>
The browser will activate the new tab when it is created, and your popup will be closed. Therefore, the callback is never called from chrome.tabs.create. The background page is a more proper place for such code.
test.html
<HTML>
<BODY>
<script type="text/javascript">
var currentWindowID = -1;
window.onload = function(e){
chrome.windows.getCurrent(function(w)
{
currentWindowID = w.id;
});
}
function openNextPage() {
var bg = chrome.extension.getBackgroundPage();
bg.openNextPage(currentWindowID);
}
</script>
<input type="button" value="Show next page" onClick="openNextPage()">
</BODY>
</HTML>
background.html
<HTML>
<BODY>
<script type="text/javascript">
function openNextPage(currentWindowID) {
console.log("in openNextPage");
chrome.tabs.create(
{url: "test2.html"},
function(tab)
{
chrome.tabs.sendRequest(tab.id, {someParam: currentWindowID})
}
);
console.log("exiting openNextPage");
}
</script>
</BODY>
</HTML>

Categories