chrome extension popup same tab still not working - javascript

I used the code I found here.
But it´s still not working out to open my link out of the popup.html in the currently active tab.
popup.html
<!doctype html>
<html>
<style>
body {
min-width: 156px;
max-width: 100%;
position: relative;
vertical-align:middle;
}
div {
margin:1px 1px 1px 1px;
}
</style>
<head>
<title>I-Serv Switcher</title>
<script src="js.js"></script>
</head>
<body>
<script src="js.js"></script>
<div style="width:50px; height:50px; background-color:blue; float:left;">Click.</div>
</body>
</html>
As you can see there is a little blue div. when i add target="_blank", then google opens in a new tab. But adding the following .js should take the link out of the clicked div with href and open it in the active tab.
js.js
var hrefs = document.getElementsByTagName("a");
function openLink() {
var href = this.href;
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
var tab = tabs[0];
chrome.tabs.update(tab.id, {url: href});
});
}
for (var i=0,a; a=hrefs[i]; ++i) {
hrefs[i].addEventListener('click', openLink);
}
the permission "tabs" is given in the manifest.json
What am i doing wrong ?
Did I forget something ?

Your code executes at the moment the <script> tag is read.
The rest of the DOM is not constructed yet; document.getElementsByTagName("a") is, therefore, empty.
To fix this, you need to wrap your code in a DOMContentLoaded event:
document.addEventListener("DOMContentLoaded", function() {
var hrefs = document.getElementsByTagName("a");
/* ... */
});
Note that you can easily debug your popup by right-clicking your extension's button and selecting "Inspect popup"

Related

Running music in the background from google chrome extension

I am making a google chrome extension, where you press certain buttons, it starts, pauses, or restarts a song. I got it working but there is one problem. When I close the extension, the song stops! I need to know if there is a way around this. I have looked into background scripts and stuff, but I can't get them to work. Please help as this is one of my first google chrome extensions, and I would like to learn more. Thanks for any help you give me!
Html: (popup.html)
<html>
<head>
<link rel="stylesheet" href="styles.css">
<script src="popup.js"></script>
</head>
<body>
<center>
<h1>Music Player</h1>
<h3>Songs:</h3>
<div id="ludicrous_speed">Ludicrous Speed
<audio id="ludicrous" src="songs/ludicrous_speed.mp3" preload="auto"></audio>
<button class="Start" id="StartLudicrous">Start</button>
<button class="Pause" id="PauseLudicrous">Pause</button>
<button class="Restart" id="RestartLudicrous">Restart</button>
</div>
</center>
</body>
</html>
Javascript: (popup.js)
function Start(song) {
song.play();
}
function Pause(song) {
song.pause();
}
function Restart(song) {
song.currentTime = 0;
}
document.addEventListener('DOMContentLoaded', function(){
var Start_Ludicrous = document.getElementById('StartLudicrous');
var Pause_Ludicrous = document.getElementById('PauseLudicrous');
var Restart_Ludicrous = document.getElementById('RestartLudicrous');
Start_Ludicrous.addEventListener('click', function() {
Start(ludicrous);
});
Pause_Ludicrous.addEventListener('click', function() {
Pause(ludicrous);
});
Restart_Ludicrous.addEventListener('click', function() {
Restart(ludicrous);
});
});
CSS: (styles.css)
body {
width:300px;
}
.Start {
background-color: #42f46e;
border-color: #42f46e;
border-radius: 30%;
}
.Pause {
background-color: #f4e349;
border-color: #f4e349;
border-radius: 30%;
}
.Restart {
background-color: #e03838;
border-color: #e03838;
border-radius: 30%;
}
Manifest: (manifest.json)
{
"manifest_version":2,
"name":"Music Player",
"description":"Play Music",
"version":"1.0",
"browser_action":{
"default_popup":"popup.html"
},
"permissions":[
"activeTab"
]
}
The document that popup.html creates exists only as long as it's open.
The moment the popup closes the <audio> element no longer exists.
A background page provides a solution to that - it exists independently of the popup.
You don't normally create a background page's HTML yourself, only provide a bunch of scripts. But nothing stops you from creating a DOM node on the fly:
// background.js
var audio_element = document.createElement("audio");
audio_element.src = "songs/ludicrous_speed.mp3";
audio_element.play();
Now, the popup's code won't be able to directly access the audio_element of the background page; you could do a quick hack job with getBackgroundPage methods, but it's preferable to learn how Messaging works and use chrome.runtime.sendMessage from the popup to control the background.

Loading JavaScript in a Chrome Extension

This is my first post on SO and my first time making a Chrome Extension. I've read alot of documentation, but I am still unsure how to get this to work. Below are my html and js files. I want to be able to type something in the source box and have the have the word print out in the results area in real time. I have tested this code on my local host so i know it works, but for some reason it is acting up as a chrome extension.
popup.html
<!doctype html>
<html>
<head>
<title>Getting Started Extension Popup</title>
<style>
body {
min-width: 357px;
overflow-x: hidden;
}
img {
margin: 5px;
border: 2px solid black;
vertical-align: middle;
width: 75px;
height: 75px;
}
</style>
<script src="popup.js"></script>
</head>
<body>
<textarea id="source"></textarea>
<div id="result">
</div>
</body>
</html>
Here's the js:
function main() {
document.getElementById('source').keydown(function() {
var source = document.getElementById('source').value;
var outputValue = source.replace(/command/gi, "⌘")
.replace(/tab/gi, "⇥")
.replace(/return/gi, "⏎")
.replace(/option/gi, "⌥")
.replace(/control/gi, "⌃")
.replace(/esc/gi, "⎋")
.replace(/left/gi, "←")
.replace(/down/gi, "↓")
.replace(/up/gi, "↑")
.replace(/right/gi, "→")
.replace(/shift/gi, "⇧")
.replace(/eject/gi, "⏏")
.replace(/caps\s\(lock\)/gi, "⇪")
.replace(/save/gi, "⌘ + S")
.replace(/print/gi, "⌘ + P")
.replace(/find/gi, "⌘ + F");
document.getElementById("result").innerHTML = outputValue;
}
}
1) What wOxxOm said in the comment: element.keydown(function() { ... }) does not exist. This definitely comes from some jQuery code - you could use that if you add it to your extension, or you could use addEventListener.
2) You declare a function main(), but nothing ever calls it. A good place to call it would be a DOMContentLoaded event listener on document:
document.addEventListener("DOMContentLoaded", main);
function main() {
/* ... */
}

Closing an iFrame via Javascript

I'm working on an application with modal overlays that appear within iFrames when the corresponding buttons are pressed. To close one of these modal overlays, the Cancel button is defined in the parent window this way:
Cancel
I'd like to replace this with a JavaScript function (let's call it onCancel() ) so I can reset some values if needed in addition to closing the overlay. What is the JavaScript equivalent to "#close"?
You can't close an iFrame, you either have to remove or hide it. The example below removes the iframe. If you just want to hide you can replace the last line (containing removeChild with this one frame.style.display="none"; You can then get it back by using this line frame.style.display="block";
<!DOCTYPE html>
<head>
<title>test</title>
<style type="text/css">
.top {
height: 100px;
width: 200px;
background-color: blue;
}
</style>
<script type="text/javascript">
function removeIFrame() {
var frame = document.getElementById("iframe");
frame.parentNode.removeChild(frame);
}
</script>
</head>
<body>
<div class="top" onclick="removeIFrame();"></div>
<iframe id="iframe" src="/" width="200" height="100"></iframe>
<div class="top"></div>
</body>
<!DOCTYPE html>
<head>
<title>test</title>
<style type="text/css">
.top {
height:100px;
width:200px;
background-color:green;
}
</style>
<script type="text/javascript">
function removeIFrame() {
var frame = document.getElementById("target");
frame.parentNode.removeChild(frame);
}
</script>
</head>
<body>
<div class="top" onclick="removeIFrame();"></div>
<iframe id="target" src="http://www.disney.com" width="100" height="100"></iframe>
<div class="top"></div>
</body>
The approach that works for me is to define the following JavaScript function in the parent page:
function onCancel()
{
var myIFrame = document.getElementById("myIFrame");
var myForm = myIFrame.contentDocument.myForm;
var stuffWasChanged = myIFrame.contentDocument.stuffWasChanged;
if (stuffWasChanged == "true")
myForm.action = "reset.do";
myForm.submit();
location.href = '#';
}
Note that if the stuffWasChanged flag was not set to true, then no action is defined for the form in question, so the modal overlay simply goes away without any servlet method being called.

Chrome extension security policy for dynamic URLs on new tabs

Im simply trying to get text from a input and from there open a URL with a newtab/window (either or) with this value included in the URL.
Example
<html>
<head>
<title>Getting Started Extension's Popup</title>
<style>
body {
min-width: 357px;
overflow-x: hidden;
}
img {
margin: 5px;
border: 2px solid black;
vertical-align: middle;
width: 75px;
height: 75px;
}
</style>
</head>
<body>
<input type="text" name="enter" class="enter" value="9999" id="lolz"/>
<input type="button" value="click" />
</body>
</html>
popup.js (Unsure about)
chrome.browserAction.onClicked.addListener(function(activeTab){
document.getElementById('lolz').value
var newURL = "https://stackoverflow.com/" + value;
chrome.tabs.create({ url: newURL });
});
So the end result is a new window with the url "https://stackoverflow.com/9999"
Currently im getting the following error.
Refused to execute inline event handler because it violates the following Content Security Policy directive: "script-src 'self' chrome-extension-resource:".
This is on the popup.html:30
You can't have inline scripts or function calls in your html (e.g. onclick for your input button)
Add the script with src to the head section
<head>
...
<script src="popup.js"></script>
</head>
Add an id to your button.
popup.js should look like this:
document.addEventListener('DOMContentLoaded', function () {
document.querySelector('input#yourButtonID').addEventListener('click', popup);
});
function popup()
{
var newURL = "http://stackoverflow.com/" + document.getElementById("lolz").value;
chrome.tabs.create({ url: newURL });
}
Change yourButtonID with the actual id.

iframe parent document element

This should work according to all the stuff I've looked up, but it just doesn't.
I have a html with a document. It has a div, which contains a specific element which I want to access.
<li>FAQ</li>
The html document also contains an iframe with the FAQ.html, which has the following loadup code:
<script>
function loaded() {
parent.document.getElementById("Faq").style.color = "green";}
</script>
However, nothing happens. What am I doing wrong?
The error console reports nothing which could facilitate my analasys.
EDIT:
Here's a basic concept.
https://dl.dropbox.com/u/32831239/Screenshots/htmlstructure.png
(Unfortunately stackoverflow doesn't let me post images as of now)
The left div should serve as a nav bar. Upon page load, the li entry should be marked with a color (e.g. green).
Use onload event of the body of FAQ.html to invoke loaded function
<html>
<head>
<script>
function loaded() {
alert("Hello !"); //alert to check if this is being invoked.
parent.document.getElementById("Faq").style.color = "green";
}
</script>
</head>
<body onload="loaded();" >
...
</body>
</html>
Or just remove the function (no need to use body onload event)
<script>
parent.document.getElementById("Faq").style.color = "green";
</script>
<iframe src="test1.html"
style="float: right;
width: 260px; height: 130px;
margin-left: 12px; border: 1px solid black;"
name="#boogiejack">
Alternative Content
</iframe>
Test1.html content
<li>FAQ</li>
<script type="text/javascript">
function loaded() {
document.getElementById("Faq").style.color = "green";}
</script>
You could use the following in your parent
var iframe = document.createElement("iframe");
iframe.src = urlToYourIframe;
// if this is IE then use attachEvent
if (iframe.attachEvent){
iframe.attachEvent("onload", function(){
parent.document.getElementById("Faq").style.color = "green";
});
} else {
iframe.onload = function(){
parent.document.getElementById("Faq").style.color = "green";
};
}
var el = document.getElementById("iFrameContainer");
el.appendChild(iframe);​

Categories

Resources