Unable to call JavaScript function in html on button click - javascript

I was making a Chrome extension, for which I have an html file, a JavaScript file which opens a modified link in a new tab, the manifest file and the icon.
It works fine but now I want the javascript function to work only when the user clicks a button. So I made a button in the html file, put the js code inside a function and called the function using onclick.
But for some reason, it is not working. On clicking the button nothing seems to happen. I have tried reloading the extension. Also, I took a working example of a simple program in which on clicking the button, a simple "Hello world" message is displayed using alert().
This works fine when I open the html page directly in chrome but when I replaced this with the function that I made, nothing seems to happen on clicking.
Can someone please find the bug/problem?
The urltry.html file is:
<!DOCTYPE html>
<html>
<button onclick="editorial()">View Editorial</button>
<script>
function editorial()
{
chrome.tabs.query({currentWindow: true, active: true}, function(tabs){
var tab_url=tabs[0].url;
var new_url=tab_url.slice(11);
chrome.tabs.create({ url:"http://www.discuss." + new_url});
});
}
</script>
</html>

Due to the default Content Security Policy (CSP) in Google Chrome extensions, the following is disallowed:
Eval and related functions
Inline JavaScript
The suggestion, as provided by Google Chrome Extensions documentation on SCP is to place the code to a separate file and use proper binding to click event from JavaScript. See below.
Your HTML file:
<!DOCTYPE html>
<html>
<head>
<script src="editorial.js"></script>
</head>
<body>
<button id="viewEditorial">View Editorial</button>
</body>
</html>
Your JavaScript file, editorial.js
function editorial() {
chrome.tabs.query({currentWindow: true, active: true}, function(tabs){
var tab_url=tabs[0].url;
var new_url=tab_url.slice(11);
chrome.tabs.create({ url:"http://www.discuss." + new_url});
});
}
document.addEventListener('DOMContentLoaded', function () {
var btn = document.getElementById('viewEditorial');
if (btn) {
btn.addEventListener('click', editorial);
}
});
Note: don't forget that you need to declare "tabs" permission to be able to modify the URL. See the tabs documentation.

You must put your button inside the body tag, otherwise many bad things can happen and probably the browser goes in the quirks mode.
Solution:
<!DOCTYPE html>
<html>
<head>
<script>
function editorial()
{
chrome.tabs.query({currentWindow: true, active: true}, function(tabs){
var tab_url=tabs[0].url;
var new_url=tab_url.slice(11);
chrome.tabs.create({ url:"http://www.discuss." + new_url});
});
}
</script>
</head>
<body>
<button onclick="editorial()">View Editorial</button>
</body>
</html>

You can try with this,
<body>
<button onclick="javascript:editorial()">View Editorial</button>
</body>
This will work in Microsoft EDGE browser also.

Related

Open a HTML page on new tab on the event of Button click from Popup of Chrome Extension and send data retrieved from current tab

There is this SO question similar to my question - Send message to background page, update the html, and then show it in a tab. But I'm first running a JS script in the context of the current tab i.e., this script to find the highlighted word is injected into the current web page. So, I'm unable to use chrome APIs.
I am trying to make a Chrome extension that fetches the meaning of the highlighted/selected word after clicking a button on the extension's popup. Here's my popup.html:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="button.css" />
</head>
<body>
<button id="meaning" type="button">Find Meaning</button>
<script src="popup.js"></script>
</body>
</html>
Here's my popup.js:
const meanButton = document.getElementById("meaning");
meanButton.addEventListener("click", async () => {
let [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
chrome.scripting.executeScript({
target: { tabId: tab.id },
function: findMeaning,
});
});
function findMeaning(){
const word = window.getSelection().toString();
// code to send the word to another HTML file that opens in a new tab
}
Let's say, I've a mean.html in my extension's directory and it is like:
<html>
<body>
<p id="para"> the answer appears here </p>
<script>
function showMeaning(wordToFindMeaning) {
const meaning = await fetch(`someAPI/${wordToFindMeaning}`);
document.getElementById('para').innerText = meaning;
}
showMeaning(word);
</script>
How do I pass the highlighted word from popup.js to this mean.html. I don't know if chrome.storage API could be used. If we use it, the word shouldn't persist in the memory after the mean.html page is opened and the word meanings are displayed.

How to automatically close a browser tab after it opens when I run a GET request in a Google apps script

I'm calling a Google Apps Script webapp with a GET request by clicking a link to the webapp's Url, to initiate a function.
The browser automatically opens a tab with the return response.
How can I automatically close that tab immediately or after a few seconds of displaying a message.
I looked around and saw alot of suggestions to add a <script> tag, But it doesn't seem to work. Where am I going wrong?
Code.gs
function doGet(e) {
var pram = e.parameter.param;
// Run some code based off of the parameter
return HtmlService.createHtmlOutputFromFile('confirmation');
}
HTML file
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
function start(){
setTimeout(function(){ window.top.close(); }, 3000);
}
</script>
</head>
<body onload="start()">
<h2 style="text-align: center;">Your function is being Initiated<br>Please Wait...</h2>
</body>
</html>
The short answer is this cannot be done. please see #TheMaster's comment.

Automatically Type In Current Tab Search Bar-Chrome Extensions

I am just learning JavaScript primarily to automate searches on a specific website and compare some data that is gathered from those searches. Thus I was wondering if it would be possible to do such a thing with a search bar in that site with JavaScript in my chrome extension I want to create.
Note: an example of a search bar in a website would be like YouTube's search bar
Edit: After doing far more research, I found that forum.submit might be of use, but I am not too sure.
EDIT 2:
extension_ui.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>extension_ui</title>
</head>
<body>
<button>Start</button>
<script src="find_time_slots.js" charset="utf-8"></script>
</body>
</hmtl>
find_time_slots.js
document.addEventListener('DOMContentLoaded', function(){
document.querySelector('button').addEventListener('click',onclick,false)
function onclick(res){
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.executeScript(
res.tabNum,
{code: 'document.getElementById("search").value = "overwatch";'}
);
})
}
},false)
content.js
chrome.runtime.onMessage.addListener(function(request,sender,sendResponse){
sendResponse({tabNum: sender.id})
});
Although I am not getting any errors, it does not update the search bar(on youtube) to ethier have "overwatch" as its value or show up in the youtube page.
You need find the id of search bar. In youtube the id is search;
In your popup.js using chrome.tabs.executeScript and it need put in a listener event.
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.executeScript(
tabs[0].id,
{code: 'document.getElementById("search").value = "' + /*you value*/ + '";'}
);
});
Hope that can help you

Edit page HTML through external Javascript in a Chrome Extension

I'm working on my first extension ever and I'm somewhat stuck with it, so I'd like the community to give me some orientation on how to do it.
What I want to do is a basic Tab manager, which in first place should (1) read all the open tabs in the browser, (2) display them in a webpage, and (3) allow reordering in the webpage and reflect that in the browser itself.
UPDATED
So far I've already done (1) with the following code in a file named eventPage.js:
chrome.browserAction.onClicked.addListener(function(activeTab){
var newURL = "main.html";
chrome.tabs.create({ url: newURL });
});
chrome.tabs.query({}, function(tabs) {
console.log(tabs);
for (var i=0; i<tabs.length; i++) {
var tabURL = tabs[i].url;
console.log(tabURL);
writeURL(tabURL);
}
});
function writeURL(tabURL) {
var node = document.getElementById('div1');
node.innerHTML = '<p>' + tabURL + '</p>';
}
Where I'm having problems is with (2) because I don't know how to display the information of the tabs in the newly opened main.html; as far as I understand and tested, I can't add script content in the body of the main.html file.
UPDATED
The main.html file at this point doesn't do a thing, what i'd like to do is print all far just
<!doctype html>
<html>
<head>
<title>Tab & Window Manager</title>
<script src="eventPage.js"> </script>
</head>
<body>
Just testing
<div id="div1">
<p id="p1">This is part of the native HTML.</p>
</div>
</body>
</html>
The output I get so far is:
just the last tab, which actually is the extension tab, but I want all tabs to be listed.
So, how can I display all the tabs information in the newly opened html file and what's the best way to do it? I haven't found any example or guide about this specific use case.
Any help will be greatly appreciated.

I want to do function at open Chrome with web site Javascript

I'm new at Javascript and I have a question.
I want to at start if I open Chrome and web site to do my function.
I want to every time do this function if I open Google Chrome!
I have adblock, and I want if every time I open this web site how2play.pl I want to delete this window scr.hu/0qbal/i9wa2 with code scr.hu/0qbal/gs9sy like in console paste document.getElementById('sdf09-8e9daf9e854f26f98cabf235ad8343cb').style.display = "none";
Please explain step by step.
<!doctype html>
<html>
<head>
<title>Testing</title>
</head>
<body>
<script type="text/javascript">
window.onload = function()
{
alertme('this works');
};
function alertme(text)
{
alert(text);
}
</script>
<button onclick="alertme('you clicked me');">Click Me</button>
</body>
</html>
When the page is done loading or if you click on the button, the code will run a javascript function that will display an alert box.
How it works
In the javascript there is a window.onload = function() -- which allows you to run any function you want immediately when the page is done loading (in this example it will run the alertme('this works');)
When you look at the button you will see that the button contains alertme('you clicked me');
That is also a function that executes when the button is clicked.

Categories

Resources