Google Chrome Extensions: Passing user highlighted webpage text to a browser_action - javascript

I'm working on a Chrome extension where I need to pass highlighted text into a browser_action. I found the following code in a Google Group, and at the time it was written it was still valid - but it doesn't work anymore..
Does anyone know an alternative solution?
background.html:
<html>
<head>
<script type="text/javascript">
var selection_callbacks = [];
function getSelection(callback) {
selection_callbacks.push(callback);
chrome.tabs.executeScript(null, { file: "contentscript.js" });
};
chrome.extension.onRequest.addListener(function (request) {
var callback = selection_callbacks.shift();
callback(request);
});
</script>
</head>
<body>
</body>
</html>
popup.html:
<html>
<head>
<script type="text/javascript">
function onSelection(text) {
document.getElementById("output").innerHTML = text;
}
chrome.extension.getBackgroundPage().getSelection(onSelection);
</script>
</head>
<body>
<div id="output">
This should be replaced with the selected text
</div>
</body>
</html>
contentscript.js:
chrome.extension.sendRequest(window.getSelection().toString());

You could use a real content script instead of injecting JavaScript into the page with chrome.extension.executeScript. You could then have background.html ask the content script for the selection using chrome.tabs.sendRequest.

Related

Why am I having an error connecting javascript to simple html?

I am attempting to connect szimek's signature pad to my simple html document. I am testing out the program but cannot get it working in my atom text editor:
html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript">
"https://cdn.jsdelivr.net/npm/signature_pad#3.0.0-beta.3/dist/signature_pad.min.js"
</script>
</head>
<h1>
Please Sign
</h1>
<div class="wrapper">
<canvas id="signature-pad" class="signature-pad" width=400 height=200></canvas>
</div>
<div>
<button id="save">Save</button>
<button id="clear">Clear</button>
</div>
<script src="script.js"></script>
</body>
</html>
script.js
var signaturePad = new SignaturePad(document.getElementById('signature-pad'), {
backgroundColor: 'rgba(255, 255, 255, 0)',
penColor: 'rgb(0, 0, 0)'
});
var saveButton = document.getElementById('save');
var cancelButton = document.getElementById('clear');
saveButton.addEventListener('click', function (event) {
var data = signaturePad.toDataURL('image/png');
// Send data to server instead...
window.open(data);
});
cancelButton.addEventListener('click', function (event) {
signaturePad.clear();
});
I have put the same code into js fiddle, and the project works fine. I am connecting through a CDN, and the error I am getting in my own project's inspection is:
script.js:1 Uncaught ReferenceError: SignaturePad is not defined
at script.js:1
<script type="text/javascript">
"https://cdn.jsdelivr.net/npm/signature_pad#3.0.0-beta.3/dist/signature_pad.min.js"
</script>
Does not load the script https://cdn.jsdelivr.net/npm/signature_pad#3.0.0-beta.3/dist/signature_pad.min.js it is a script containing the string "https://cdn.jsdelivr.net/npm/signature_pad#3.0.0-beta.3/dist/signature_pad.min.js"
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/signature_pad#3.0.0-beta.3/dist/signature_pad.min.js"></script>
Your script tag is wrong.
<script type="text/javascript">
JS CODE
</script>
This tag is used to include JS code in your page. The line JS CODE is intended to be the code. If you want to pull in an external script, the above code is not the right way to do that.
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/signature_pad#3.0.0-beta.3/dist/signature_pad.min.js">
</script>
The key here is your script tag needs to specify the location where your browser can find the script. It does this using the src attribute on the script tag. As you currently have it, you have some code containing a single string, which doesn't do much.
Instead of:
<script type="text/javascript">
"https://cdn.jsdelivr.net/npm/signature_pad#3.0.0-beta.3/dist/signature_pad.min.js"
</script>
Use:
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/signature_pad#3.0.0-beta.3/dist/signature_pad.min.js"></script>

Problems with including external JS file to HTML

I've read many tutorials and tried them, but they don't work.
Just for example I wrote this simple code:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p id="testElement"> Html text</p>
<script>
var paragraph = document.getElementById("testElement");
paragraph.innerHTML = "Test Message";
</script>
</body>
</html>
I get Test Message text in my page.
Then I put my JS code to an external file: '/js/js.js'
var paragraph = document.getElementById("testElement");
paragraph.innerHTML = "Test Message";
And modify the HTML file to:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="/js/js.js"></script>
</head>
<body>
<p id="testElement"> Html text</p>
</body>
</html>
When I open the HTML file in a browser, I only get Html text. My JS does not work. Please explain what I am doing wrong.
Your problem is that javascript linked in head is executed before the body is loaded, so you can just put the script at the end of the body like this:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p id="testElement"> Html text</p>
<script type="text/javascript" src="js/js.js"></script>
</body>
</html>
Check the JavaScript error console.
Your code runs before the document is rendered so the node testElemet doesn't exist.
Either move your script-include down as the last element in the body or wrap your code in a load/ready event.
function on_document_ready(callback) {
if (document.readyState === "complete") {
callback();
} else {
document.addEventListener("DOMContentLoaded", callback);
}
}
on_document_ready(function () {
var paragraph = document.getElementById("testElemet");
paragraph.innerHTML = "Test Message";
});
This should work fine:
var paragraph = document.getElementById("testElement");
paragraph.innerHTML = "Test Message";
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p id="testElement">Html text</p>
<script type="text/javascript" src="/js/js.js"></script>
</body>
</html>
Please make sure that <script type="text/javascript" src="/js/js.js"></script> is placed just before </body>.
Try this
var doSomething = function()
{
var paragraph = document.getElementById("testElement");
paragraph.innerHTML = "Test Message";
}
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="js.js"></script>
</head>
<body onload = "doSomething();">
<p id="testElement"> Html text</p>
</body>
</html>
Try saving both the files in the same folder.
Make use of your browsers developer console, to determine whether any errors have occurred.
Regarding 'onload', you can have a look at this link.

alert in javascript not showing

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
if (document.getElementById("popup")) {
window.alert("hi");
}
</script>
</head>
<body>
<h1 id="popup">dfdfs</h1>
</body>
</html>
i have a simple javascript which shows alert when the h1 id exits ,but i am not getting the alert message.code in jquery also can help.
Put your <script> tag at the end of the body:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1 id="popup">dfdfs</h1>
<script type="text/javascript">
if (document.getElementById("popup")) {
window.alert("hi");
}
</script>
</body>
</html>
Write your script after the element so that it runs after element is present. See the code:
<!DOCTYPE html>
<html>
<body>
<h1 id="popup">dfdfs</h1>
<script type="text/javascript">
if (document.getElementById("popup")) {
window.alert("hi");
}
</script>
</body>
</html>
Plunkr for the same is: "http://plnkr.co/edit/0fznytLHtKNuZNqFjd5G?p=preview"
Because, you're executing the script before document is completely loaded, the element #popup is not found.
Use DOMContentLoaded
Use DOMContentLoaded to check if the DOM is completely loaded.
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function(event) {
console.log("DOM fully loaded and parsed");
if (document.getElementById("popup")) {
window.alert("hi");
}
});
</script>
Using jQuery ready
Using jQuery, you can use ready method to check if DOM is ready.
$(document).ready(function() {
if ($("#popup").length) {
window.alert("hi");
}
});
Moving script to the end of body
You can move your script to the end of body.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1 id="popup">dfdfs</h1>
// Move it here
<script type="text/javascript">
if (document.getElementById("popup")) {
window.alert("hi");
}
</script>
</body>
</html>
Your script is above the h1 element that you're trying to retrieve. Because of this, it is being run before the element actually exists.
Either move the script to the bottom of the page, or wrap it in a jQuery ready block. And consider moving it to an external file.
$(function() {
if(document.getElementById("popup")) {
window.alert("hi");
}
});
try this easy way. no need of jquery.
<html>
<head>
</head>
<body>
<h1 id="popup">dfdfs</h1>
<script type="text/javascript">
if(document.getElementById("popup")) {
window.alert("hi");
}
</script>
</body>
</html>
It is good practice to use the <script> tags in <body> because it improves the performance by loading it quicker.
And then use
<body>
<script>
$(function() {
if(document.getElementById("popup")) {
window.alert("hi");
}
});
</script>
</body>
Below code gives you solution
$(document).ready(function() {
if (document.getElementById("popup")) {
window.alert("hi");
}
});

Change LaTeX when button is pressed

I am trying to create a program that generates random functions then shows them in LaTeX but I can't figure out how to edit LaTeX when a button is pressed.
This code works:
<html>
<head>
<script type="text/javascript" src="http://latex.codecogs.com/latexit.js"></script>
</head>
<body>
<div lang="latex" id='Latexdiv'></div>
<script>
document.getElementById('Latexdiv').innerHTML = 'sin(x)';
</script>
</body>
</html>
But this does not:
<html>
<head>
<script type="text/javascript" src="http://latex.codecogs.com/latexit.js"></script>
</head>
<body>
<div lang="latex" id='Latexdiv'></div>
<button onclick="change();">Change the LaTeX</button>
<script>
function change()
{
document.getElementById('Latexdiv').innerHTML = 'sin(x)';
}
</script>
</body>
</html>
I tried to use MathJax like this:
<html>
<body>
<button onclick='change();'>Change the LaTeX</button>
<div lang='latex' id='Latexdiv'></div>
<script type='text/javascript'>
var latexdiv = document.getElementById('Latexdiv');
function change()
{
var latex = document.createElement('script');
latex.src = 'http://latex.codecogs.com/latexit.js';
document.head.appendChild(latex);
var mathjax = document.createElement('script');
mathjax.src = 'https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML';
document.head.appendChild(mathjax);
latexdiv.innerHTML = '\\(sin(x)\\)';
};
</script>
</body>
</html>
This, unfortunately, only works the first time you press the button. If you press it twice, it just shows "\(sin(x)\)" in regular HTML. How would you get it to work twice?
http://latex.codecogs.com/latexit.js executes at the end:
LatexIT.add('*');
That adds and onload listener that executes a render function, that's why works in the first case, the page ends loading after your first script.
You could simply add the render function in your change function.
function change()
{
document.getElementById('Latexdiv').innerHTML = 'sin(x)';
LatexIT.render('*',false);
}

Stop Iframe Refresh/Reload Loop When using Onload

EDIT I Found the solution! credit goes entirely to the assistance I received from Mixel. For those who find themselves in the same predicament of needing to pull a div from an iframe without using onload here is the entire working code that I am using:
<html>
<head>
<title>Main page</title>
<style type="text/css">#hiddenframe {display:none;}</style>
<script type="text/javascript">
window.onload = function () {
var myUrl = "test.html"
document.frames['hiddenframe'].location.href = myUrl;
}
</script>
</head>
<body>
<div id="parent-div"></div>
<iframe id="hiddenframe"></iframe>
</body>
</html>
And the Child Page:
<html>
<head>
<title>Child Page</title>
<script type="text/javascript">
window.onload = function () {
parent.document.getElementById('parent-div').innerHTML = document.getElementById('daughter-div').innerHTML;
}
</script>
</head>
<body>
<div id="daughter-div">
This is the Child Div!
</div>
</body>
</html>
Thank you once again to Mixel for his help and patience in finding a solution
That's because you reload hiddenframe in onload handler. Reloading triggers onload event, then onload handler reloads hiddenframe. And this happens again and again...
Edit:
May be I do not understand what you want to do in your code, but if you want to load iframe when parent window is loaded you need this:
window.onload = function () {
document.getElementById('hiddenframe').setAttribute('src', 'test.html');
}
And there is window.onload handler of test.html page:
window.onload = function () {
parent.document.getElementById('parent-div').innerHTML = document.getElementById('daughter-div').innerHTML;
}
Edit2:
That's html of main page:
<div id="parent-div"></div>
<iframe id="hiddenframe">
</iframe>
And that's test.html:
<div id="daughter-div">
Child div!
</div>

Categories