I've been having trouble with Firefox not executing JavaScript files that were loaded dynamically via an external script.
Let me explain.
I have the following HTML file:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Restive.JS</title>
<meta name="keywords" content="">
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="text/javascript" src="assets/js/load.js"></script>
</head>
<body>
<h1>Loading JavaScript</h1>
</body>
</html>
Inside my load.js file, I have the following code:
document.addEventListener("DOMContentLoaded", function() {
function loadScript(url) {
var script = document.createElement("script");
script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
}
var list_arr = ['assets/js/test1.js', 'assets/js/test2.js'];
for (var i = 0; i < list_arr.length; i++) {
loadScript(list_arr[i]);
}
});
And inside test1.js and test2.js, I have console.log('test1.js is loaded!'); and console.log('test2.js is loaded!');.
The problem is that test1.js and test2.js are loaded (I can see both files in the <head> via inspection), but they are never executed (because no messages appear in the console log).
However, when I change the format of script reference in my original HTML by inlining the JavaScript i.e. changing from this:
<script type="text/javascript" src="assets/js/load.js"></script>
to this:
<script>
document.addEventListener("DOMContentLoaded", function() {
function loadScript(url) {
var script = document.createElement("script");
script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
}
var list_arr = ['assets/js/test3.js', 'assets/js/test4.js'];
for (var i = 0; i < list_arr.length; i++) {
console.log('i = ' + i);
loadScript(list_arr[i]);
}
});
</script>
Then the scripts are loaded and executed.
I don't see this behaviour in Chrome or Safari, only Firefox. Also, inlining is not an option because this functionality is built-in to a library that users will have to reference via an external link.
Is this a problem that is fixable?
EDIT
I'm on a Mac OSX 10.10.5 using Firefox 46.0.1
Related
I create a simple code to extract URL from a website
but it's not working when I click on icon extensions
My js code
var el = document.getElementById('myPopup');
el && el.addEventListener('click', yourFunction, false);
function yourFunction() {
let x = document.querySelectorAll("a");
let myarray = [];
for (let i = 0; i < x.length; i++) {
let nametext = x[i].textContent;
let cleantext = nametext.replace(/\s+/g, " ").trim();
let cleanlink = x[i].href;
myarray.push([cleantext, cleanlink]);
}
function make_table() {
let links_table = "<table><thead><th>Name</th><th>Links</th></thead><tbody>";
for (let i = 0; i < myarray.length; i++) {
links_table += "<tr><td>" + myarray[i][0] + "</td><td>" + myarray[i][1] + "</td></tr>";
}
let w = window.open("");
w.document.write(links_table);
console.log(w);
console.log(links_table);
}
make_table();
}
yourFunction();
My HTML code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<dev>
<button id="myPopup">Clickme</button>
</dev>
<script src="popup.js"></script>
</body>
</html>
when i click on Clickme the url not show me just empty table
can you tell me where is the Error?
video
imgur.com/a/0OS60qG
The error happens since the popup script does not have access to the list of "a" tags. When you ran it on the browser console it works cause you are manipulating the page content, meanwhile, on the popup, it only interacts with the popup.html page.
Content scripts should be the only scripts able to manipulate the page content, so to fix that you probably should send a message to a content script when clicking on the button, so the content script can scrap the links and send them as a response to the popup or output as you want.
This other question may help you to see how to send messages between files:
How to send the message from popup.html to content script?
I added an event listener to my website which should add a date, time and device-id to the website. These information are included in the filenames of some files located in a directory at the same level as my index.html.
Directory Structure:
- audiofiles
-- date_time_device.wav
-- date2_time2_device2.wav
- scripts
-- scripts.js
- Home.html
Within the head of Home.html I'm calling a addContent() (located in scripts.js) which includes the addEventListener().
This works if I'm inserting hardcoded strings, so it seems that reading from the directory does not work.
It would be great if anybody could steer me into the right direction. Thanks!
Head of Home.html:
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://unpkg.com/wavesurfer.js"></script>
<script type="text/javascript" src='scripts/scripts.js'> </script>
<script type="text/javascript" src="js/wavesurfer.js"></script>
<script>
addContent();
</script>
<title>Home</title>
</head>
scripts.js:
function addContent() {
document.addEventListener("DOMContentLoaded", function(event) {
var fs = require('fs');
const files = fs.readdirSync('path/to/audiofiles');
for (i=0;i<3;i++) {
var date = files[i].slice(0,10);
var time = files[i].slice(11,19);
var device = files[i].slice(20,-4);
var TheInnerHTML ="";
TheInnerHTML += "<tr><td> blabla" + 3 + " " + String(date)+"</td><td>"+String(time)+"</td></tr>"+String(device)+"</td></tr><br>";
}
document.getElementById("TheBody").innerHTML = TheInnerHTML;
});
}
I need my webite to display info in a certain language, based on a query in my webite's URL (e.g. www.website.com/index.php?country=FR). How can I do that with vanilla JS and not React/Angular?
My approach:
1) JS recognizes a query in the URL (in this case- 'country=FR') and then appends a js file, which has neccessary french words in it defined by variables.
2) JS in my script tag that's in the HTML file, appends the main page markup text with template literals in it.
3)
I don't know, whether the browser fails to either fetch the language file itself or its variables. At the moment it does not render anything.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="./js/main.js"></script>
</head>
<body>
<script>
const template= `
<h1>Good Morning: ${goodmorning} </h1>
<h2>Good Evening: ${goodevening} </h2>
<h3>My name is: ${mynameis}</h3>`
function markupAppend() {
$('body').html(template);
console.log('Markup loaded')
}
markupAppend()
</script>
</body>
</html>
=========================
Main.js
var domain = window.location.href;
var FRString = domain.includes("country=FR");
var ESString = domain.includes("country=ES");
if (FRString) {
$('head').append(`<script src="./Language_files/FRENCHwords.js" />`)
}
if (ESString) {
$('head').append(`<script src="./Language_files/SPANISHwords.js" />`)
}
=========================
FRENCHwords.js
const goodmorning = 'Bonjour';
const goodevening = 'Bonsoir';
const mynameis = 'Mon nom est';
=========================
SPANISHwords.js
const goodmorning = 'Buenos dias';
const goodevening = 'Buenas tardes';
const mynameis = 'Mi nombre es';
No errors displayed, the page is just not rendering...
In Your main.js file, you are using domain.includes, it only returns the domain name but not the entire URL. You can use window.location.href.includes for this.
Instead of: domain.includes("country=FR");
Try: window.location.href.includes("country=FR");
How to append the HTML code snippet to HTML iframe using jquery? Actually, I have added an HTML code snippet in MySQL Database using PHP. Now I have fetched that HTML Code snippet and trying to append that HTML code snippet in iframe using jquery.
$( document ).ready(function() {
var snippets='<?php echo $snippets_preview; ?>';
$(function() {
var $iframe = $('#iframehtml');
$iframe.ready(function() {
$iframe.contents().find("body").append(snippets);
});
});
});
But I am getting the following error
Uncaught SyntaxError: Invalid or unexpected token
snippets_preview has the following value in it. when I change the value of snippet_preview. it works fine.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style>'.$postdata['snippets_css'].'</style>
<script>'.$postdata['snippets_javascript'].'</script>
</head>
<body>
'.$ContentDecodedHTML.'
</body>
</html>
If you want to embed html code in an iframe you have to do for example:
JAVASCRIPT (class)
<script>
// -------------------------------------------------------- CLASS
var class_iframe = {
// ------------------------------------- STEP 1 (Create an new Iframe)
generateIframe: function(src, targetDOM){
// ---------------- Create iframe
var newIframe = document.createElement('iframe');
newIframe.onload = function(){
class_iframe.getIframe($('.iframehtml').contents());
};
newIframe.src = src;
newIframe.className = "iframehtml";
newIframe.frameBorder = "0";
// ---------------- Insert iframe in DOM
$(targetDOM).replaceWith(newIframe);
},
// ------------------------------------- STEP 2 (Get iframe in this class)
getIframe: function(iframe){
class_iframe.frame = iframe; console.log(class_iframe.frame);
},
// ------------------------------------- STEP 3 (Append in this iframe)
appendIframe: function(targetInIframe, content){
console.log(class_iframe.frame);
$target = class_iframe.frame.find(targetInIframe); console.log($target);
$target.prepend(content);
},
}
// -------------------------------------------------------- ACTION (loadPage)
$(document).ready(function(){
//$("body").prepend(`<div id="insertIframe"></div>`); //Just for the test
class_iframe.generateIframe("your_url_iframe.html", "#insertIframe");
});
</script>
In your html page
<div id="insertIframe"></div>
JAVASCRIPT (for append in your new iframe)
<script>
// -------------------------------------------------------- ACTION (after loadPage)
class_iframe.appendIframe("html", `<div class="insert">Hello world !</div>`);
</script>
I have two scripts and I need to use script1 function in script2. Whats the best way to do it and Is there any simplification using prototype to access function in more scripts. I am using jquery.
script1
$(function(){
function process(){
// some code
}
})
script2
$(function(){
// I would like to use the process function here
}
Sample.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">
</HEAD>
<script type="text/javascript" charset="utf-8" src="Script1.js" ></script>
<script type="text/javascript" charset="utf-8" src="Script2.js" ></script>
<script>
</script>
<BODY onload='calling();'>
</BODY>
</HTML>
Scrip1.jc
function call(){
alert("Hi i am called from script2");
}
Scrip2.js
function calling(){
call();
}
Hope this help you.
You can use javascript functions as variables. So just reread your question about the same stuff about variables - Unable to access variable
So just do so your function will be available from global scope.
Just move the function declaration outside the ready event handler, that will make it globally available.
Another idea: use objects:
var Ob = {
process: function(callback) {
callback();
}
}
script1
$(function(){
Ob.process(function(){
... // code
});
});
script 2 (do same)
$(function(){
Ob.process(function(){
... //another code
});
});
If you are using same process function (means same body content, make same thing in both script) then
var Ob = {
process: function() {
...//put code
}
}
script1
$(function(){
Ob.process();
});
script 2 (do same)
$(function(){
Ob.process();
});