I've been following along on a few tutorials but have been running into examples that use deprecated code.
I'm trying to send the URL of the current tab to the popup.
My code thus far:
Manifest.json contains the proper permissions:
"permissions": [
"activeTab",
"tabs"
]
Popup.js, where I think the problem is but no errors in console.
function setup() {
noCanvas();
var url = 'URL'
function sendMessage() {
var msg = {
from: 'popup',
page: url
}
var params = {
active: true,
currentWindow: true
}
chrome.tabs.query(params, gotTabs);
function gotTabs(tabs) {
chrome.tabs.sendMessage(tabs[0].id, msg);
url = document.getElementById('currentLink').innerHTML;
console.log(url)
}
}
}
Popup.html
<body>
<h1>Popup Interface Example</h1>
<p id="currentLink">Loading ...</p>
</body>
What am I missing here?
I figured it out. Was making it WAY too hard.
Popup.js
chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) {
var url = tabs[0].url;
console.log(url);
document.getElementById("myText").innerHTML = url;
});
Popup.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Extension Pop-Up</title>
<script src="libraries/p5.js" type="text/javascript"></script>
<script src="libraries/p5.dom.js" type="text/javascript"></script>
<script src="popup.js" type="text/javascript"></script>
</head>
<body>
<h1>Wordnik Lookup</h1>
<p id="myText"></p>
</body>
</html>
Related
I'm making a chrome extension, and I'd like to pass a JS variable var job = "web"; to a php file called scan.php, and attached it to <p id="demo"></p> that is included on my HTML test page, this code works fine on my webserver but for some reasons not in my chrome extension. I don't have any error in the chrome console, so I'm not sure what to look for. Maybe something with the permission, maybe the scan.php can't be read, I tried different path with and without chrome-extension://my_chrome_extension_id/file_root_folder.php and scan.php only.
contentScript.js
(function() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("POST", "chrome-extension://XXXXXXXX/scan.php", true);
var job = "web";
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("job=" + job);
})();
Manifest V3
{
"name": "Inject MV3",
"version": "0.01",
"description": "-",
"background":{
"service_worker": "background.js"
},
"permissions": ["storage", "activeTab", "scripting"],
"host_permissions": ["<all_urls>"],
"manifest_version": 3,
"action": {
"default_popup": "popup.html"
}
}
Background.js
try{
//ON page change
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if(changeInfo.status == 'complete'){
//if (changeInfo.url) {
chrome.scripting.executeScript({
files: ['contentScript.js'],
target: {tabId: tab.id}
});
//}
}
});
}catch(e){
console.log(e);
}
Popup.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script src="contentScript.js"></script>
</body>
</html>
HTML test page where I inject my chrome extension
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p id="demo"></p>
</body>
</html>
PHP file
<?php
$job = $_POST['job'];
echo $job;
?>
I'm having an issue with my contentscript. I cannot get Jquery to function no matter what! Perhaps you can help me figure out what it is?
I am trying to "catch" a value I write in a field and pass it on for processing after I click a button. I am recieving the "$ is not defined" error which probably means it cannot load JQuery.
Here is my manifest, my html and my code:
{
"name": "Test 2017",
"manifest_version": 2,
"version": "0.1",
"description": "TestApp Jquery",
"browser_action": {
"default_popup": "popup.html",
"default_icon": "icon.png"
},
"background": {
"scripts": ["jquery-3.2.1.min.js",
"background.js"
]
},
"permissions": [
"tabs", "http://*/*", "https://*/*"
],
"content_scripts":
[
{
"matches": [ "http://*/*", "https://*/*"],
"js":["jquery-3.2.1.min.js",
"contentscript.js"]
}
]
}
Popup.html:
<html>
<head>
<script src="jquery-3.2.1.min.js"></script>
<script src="popup.js"></script>
<style type="text/css" media="screen">
body { min-width:250px; text-align: center; }
#click-me { font-size: 20px; }
</style>
</head>
<body>
<div>Input: <input id="input">
<input id="click-me" type="button" value="Go!"/>
</body>
Popup.js
function clickHandler(e) {
chrome.extension.sendMessage({directive: "popup-click"}, function(response)
{
this.close(); // close the popup when the background finishes processing
request
});
}
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('click-me').addEventListener('click', clickHandler);
})
background.js
chrome.extension.onMessage.addListener(
function(request, sender, sendResponse) {
switch (request.directive) {
case "popup-click":
// execute the content script
chrome.tabs.executeScript(null, { // defaults to the current tab
file: "contentscript.js", // script to inject into page and run in sandbox
allFrames: true // This injects script into iframes in the page and doesn't work before 4.0.266.0.
});
sendResponse({}); // sending back empty response to sender
break;
default:
// helps debug when request directive doesn't match
alert("Unmatched request of '" + request + "' from script to
background.js from " + sender);
}
}
);
Contentscript.js where I try to run Jquery:
var abc = $("#input").val();
console.log(abc);
And then I get the error.
Any help here? Why can't my extension load JQuery? I have the scripts loaded in the right order and all.
Thanks in advance!
There is no need to use a content script for what you are trying to achieve. Content scripts are used to control the DOM of the website that is loaded in your browser. The button you are trying to manipulate is in your popup window and is controlled by popup.js, not contentscript.js. Simply move the jquery code to popup.js and it should work as expected.
Content Scripts are JavaScript files that run in the context of web pages. By using the standard Document Object Model (DOM), they can read details of the web pages the browser visits, or make changes to them.
Popup.html (nothing changed here, jquery script tag is present):
<html>
<head>
<script src="jquery-3.2.1.min.js"></script>
<script src="popup.js"></script>
<style type="text/css" media="screen">
body { min-width:250px; text-align: center; }
#click-me { font-size: 20px; }
</style>
</head>
<body>
<div>Input: <input id="input">
<input id="click-me" type="button" value="Go!"/>
</body>
Popup.js:
function clickHandler(e) {
chrome.extension.sendMessage({directive: "popup-click"}, function(response)
{
this.close(); // close the popup when the background finishes processing
request
});
}
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('click-me').addEventListener('click', clickHandler);
})
var abc = $("#input").val();
console.log(abc);
I tried making a chrome extension that could give URL string of current tab of current window.
I had seen similar questions but, don't know why mine is not working.
I had taken care of deprecated calls as well.
Here it is
I have even properly set the permissions in manifest.json file.
But it's not working.
Here are main js file code
//background.js
chrome.browserAction.onClicked.addListener(function(tab) {
// Send a message to the active tab
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
var activeTab = tabs[0];
chrome.tabs.sendMessage(activeTab.id, {"message": "clicked_browser_action"});
});
});
//content.js
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if( request.message === "clicked_browser_action" ) {
var firstHref = $("a[href^='http']").eq(0).attr("href");
//console.log(firstHref);
alert(firstHref);
}
}
);
Can someone help me?
you havn't add your HTML file in your manifest file thts why your project is not working,
make some changes in your manifest.json like this :-
.......
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
....some code here//
Alternatively you can see here too for working extension of chrome
https://github.com/MrPardeep/Angular2_typescript_ChromeExtension
Edit2
Change your background.js with this code :-
document.addEventListener('DOMContentLoaded', function () {
var link = document.getElementById('btn');
// onClick's logic below:
link.addEventListener('click', function () {
AddUrl();
});
function AddUrl() {
chrome.tabs.query({ currentWindow: true, active: true }, function (tabs) {
alert(tabs[0].url)
// document.getElementById('Current_url').value = tabs[0].url;
console.log(tabs[0].url, tabs[0].title, tabs[0].incognito, tabs, this.bookmark_title);
});
}
});
and popup.html with this code :-
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<script src="background.js"></script>
<body>
<h1>This is a Heading</h1>
<button id="btn"> Click Me </button>
</body>
</html>
I am trying to use the new chrome notifications, nothing fancy just trying to a basic one to work, but i keep getting
Uncaught TypeError: Cannot call method 'create' of undefined
I think its the manifest but I'm not sure what I'm doing wrong, anyone have any ideas?
Thanks in advance
Javascript
var id= 0;
var opt={
type:"basic",
title:"Hello",
message:"world",
iconUrl:"Google.png"
}
function creationCallback(id) {
console.log("Succesfully created " + id + " notification");
}
function createnot()
{
chrome.notifications.create(id, opt, creationCallback);
id++;
}
manifest
{
"name": "Notification API Sample",
"description": "Tests the notification API",
"manifest_version" : 2,
"version" : "0.1",
"permissions" : [
"notifications"
]
}
HTML
<html>
<head>
<script type="text/javascript" src="note.js"></script>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<input type="button" value="meh" onclick="createnot()"/>
<footer>
</footer>
</body>
</html>
{
"name": "Notification API Sample",
"description": "Tests the notification API",
"manifest_version" : 2,
"version" : "0.1",
"permissions" : [
"notifications",
"http://*/*" // add this if your html file is a webpage not a page in extension.
],
"background": {
"scripts": ["background.js"],
"persistent": false // add this line if you use event page.
}
}
Your manifest.json needs the information of "background" like this.
Also, if your html page is a webpage not a page in extension itself,
You need to give a permission for it.
var id = "0";
It may not make much difference but,I think notification id needs to be a string.
chrome.notifications.create(string notificationId, NotificationOptions options, function callback)
+++Edited+++
foo.js
$(function(){
var test = $("#test");
test.click(function () {
chrome.notifications.create(
'id1',{
type:"basic",
title:"Hello",
message:"world",
iconUrl:"Google.png"
},
function() {
}
);
});
});
foo.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="jquery.js"></script>
<script src="options.js"></script>
</head>
<body>
<h1 id="test">This is a test.</h1>
</body>
</html>
manifest.json
{
"name": "Notification API Sample",
"description": "Tests the notification API",
"manifest_version" : 2,
"version" : "0.1",
"permissions" : [
"notifications"
]
}
I think this is the simplest way if the html page is in extension.
You need these files. You don't even need background.js for this.
1.manifest.json
2.foo.html
3.foo.js
I have read the documentation and this should be basic but I can't seem to get those alerts to appear. What's wrong?
popup.html
<html>
<head>
<script>
function finder() {
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.sendMessage(tab.id, {type: "feature"}, function(response) {
console.log(response.farewell);
});
});
}
</script>
<style>
p {
border: 1px solid black;
width:200px;
font-size:10px;
}
</style>
</head>
<body>
<p><a id="jira">Click to populate FE description</a></p>
<script>
var jira = document.getElementById('jira');
jira.addEventListener('click', finder, false);
</script>
</body>
</html>
Content Script:
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
alert('sreceived');
if (request.type == "feature") {
alert('score!');
}
});
Inline JavaScript will not be executed. This restriction bans both inline blocks and inline event handlers (e.g. <button onclick="...">).
By above lines it is clear that your popup.html violates restrictions, which can be solved as follows:
Remove all <script> tags in popup.html and move the original code to popup.js.
<html>
<head>
<script src="popup.js"></script> <!-- Added this line -->
<style>
p {
border: 1px solid black;
width:200px;
font-size:10px;
}
</style>
</head>
<body>
<p><a id="jira">Click to populate FE description</a></p>
</body>
</html>
I did not literally copy-paste the code in popup.js. These are the changes I made:
chrome.tabs.getSelected() is deprecated in favour of chrome.tabs.query(), so I updated chrome.tabs.getSelected(null, function(tab) {});
Commented out console.log(response.farewell); because there is no response handler from content script.
Final popup.js
function finder() {
chrome.tabs.query({
"status": "complete",
"currentWindow": true,
"active": true
}, function (tabs) {
chrome.tabs.sendMessage(tabs[0].id, {
type: "feature"
}, function (response) {
//console.log(response.farewell);
});
});
}
document.addEventListener('DOMContentLoaded',= function() {
document.getElementById('jira').onclick = finder;
});
Cautions for manifest.json
Ensured permissions are available as "permissions":["tabs","<all_urls>"],
Permissions for content script also
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"]
}
]
Final manifest.json
{
"name":"Basic Message Passing",
"description":"This demonstrates Basic Message Passing",
"browser_action":{
"default_popup":"popup.html",
"default_icon":"screen.png"
},
"manifest_version":2,
"version":"2",
"permissions":["tabs","<all_urls>"],
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"]
}
]
}
Your content script was fine, so I did not change it.
Demonstration
Output:
Let me know if you need more information..