I am trying to incorporate a Javascript function (contained in app.js), which I am trying to run from the index.html of my Angular 2 application.
Initially I used a CLI program called Office Add-in generator to make a non-angular application, in which this JavaScript works.
However when using the Add-in generator in an Angular application the app.js file is not automatically generated. Manually copy pasting the app.js file and <script> link does not work either. I realise I have only provided a couple of files worth of code, let me know if I should edit more in, or provide a github link?
The error in chrome is net::ERR_ABORTED not defined with a 404 message. (relating to the app.js file)
~~~~HTML~~~~~
<head>
<link rel="stylesheet" href="https://appsforoffice.microsoft.com/fabric/1.0/fabric.css">
<link rel="stylesheet" href="https://appsforoffice.microsoft.com/fabric/1.0/fabric.components.css">
<meta charset="utf-8">
<title>Microsoft Graph Connect sample</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<script src="https://appsforoffice.microsoft.com/lib/1/hosted/Office.js" type="text/javascript"></script>
<script>
window.history.replaceState = function(){};
window.history.pushState = function(){};
</script>
</head>
<body>
<app-root></app-root>
<button onclick="setItemBody()">Paste to email</button>
<script type="text/javascript" src="node_modules/core-js/client/core.js"></script>
<script type="text/javascript" src="node_modules/jquery/dist/jquery.js"></script>
<script type="text/javascript" src="node_modules/office-ui-fabric-js/dist/js/fabric.js"></script>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
~~~~~~~app.js~~~~~~~~
var item;
Office.initialize = function () {
item = Office.context.mailbox.item;
// Checks for the DOM to load using the jQuery ready function.
$(document).ready(function () {
// After the DOM is loaded, app-specific code can run.
// Set data in the body of the composed item.
// setItemBody();
});
}
// Get the body type of the composed item, and set data in
// in the appropriate data type in the item body.
function setItemBody() {
item.body.getTypeAsync(
function (result) {
if (result.status == Office.AsyncResultStatus.Failed){
write(result.error.message);
}
else {
// Successfully got the type of item body.
// Set data of the appropriate type in body.
if (result.value == Office.MailboxEnums.BodyType.Html) {
// Body is of HTML type.
// Specify HTML in the coercionType parameter
// of setSelectedDataAsync.
item.body.setSelectedDataAsync(
'<b>These are the times I am available:</b><br>Monday -- 8:30 to 9:00<br>Tuesday -- 1:00 to 5:00<br>Thursday -- 4:00 to 5:00<br>',
{ coercionType: Office.CoercionType.Html,
asyncContext: { var3: 1, var4: 2 } },
function (asyncResult) {
if (asyncResult.status ==
Office.AsyncResultStatus.Failed){
write(asyncResult.error.message);
}
else {
// Successfully set data in item body.
// Do whatever appropriate for your scenario,
// using the arguments var3 and var4 as applicable.
}
});
}
else {
// Body is of text type.
item.body.setSelectedDataAsync(
' Kindly note we now open 7 days a week.',
{ coercionType: Office.CoercionType.Text,
asyncContext: { var3: 1, var4: 2 } },
function (asyncResult) {
if (asyncResult.status ==
Office.AsyncResultStatus.Failed){
write(asyncResult.error.message);
}
else {
// Successfully set data in item body.
// Do whatever appropriate for your scenario,
// using the arguments var3 and var4 as applicable.
}
});
}
}
});
}
// Writes to a div with id='message' on the page.
function write(message){
document.getElementById('message').innerText += message;
}
Actually you should not just put your js files in index.html better add in .angular-cli.json file.. and about js not working in ng2+ project.. check out https://angular.io/guide/attribute-directives I think you must make wrapper. check this as well https://medium.com/#NetanelBasal/typescript-integrate-jquery-plugin-in-your-project-e28c6887d8dc
Related
I get the testFile.js filename from url parameters, so it is loaded dynamically.
Then i do:
<script>jQuery.getScript('testFolder/testFile.js');</script>
<script src="ok1.js" type="text/javascript" charset="UTF-8"> </script>
<script src="ok2.js" type="text/javascript" charset="UTF-8"> </script>
testFile.js has:
function getFile0(){}
ok1.js has:
function getFile1(){}
function getFile2(){}
function getFile3(){}
ok2.js has:
var _getFiles = [getFile0(), getFile1(), getFile2(), getFile2()];
Although, it is supposed to load first the testFile.js, then ok1.js and finally ok2.js, i get this error for ok2.js: Uncaught ReferenceError: getFile0 is not defined
I have tried plenty of stuff like:
jQuery.getScript('testFolder/testFile.js').done(function() {
jQuery.getScript('ok1.js').done(function() {
jQuery.getScript('ok2.js');
});
});
it is loading without error, but the page is not working as it should.
I have a service that I call after every 5 secs to return data from postgres table, now I want this data to be displayed on html document
app.js
const stats=app.service('test_view');
// console.log(stats);
function getstats(){
stats.find().then(response=>{
console.log('data is ',response.data)});};
setInterval(function() {
getstats();
}, 5000);
// console.log(stats);
stats.html
<!DOCTYPE html>
<html>
<head>
<title>Stats</title>
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<div id='stats'>
</div>
</body>
</html>
Everything is running fine and I am getting results in console, I am using feather.js now I want these results to be displayed in div tag of html.Please help me in this regard.
You need to call the feathers service from the browser. You can do this a number of different ways (as a REST call, with the feathers client, etc.).
<html lang="en">
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/core-js/2.1.4/core.min.js"></script>
<script src="//unpkg.com/#feathersjs/client#4.0.0-pre.3/dist/feathers.js"></script>
<script src="//unpkg.com/axios/dist/axios.min.js"></script>
<script>
// #feathersjs/client is exposed as the `feathers` global.
const app = feathers();
app.configure(feathers.rest('http://localhost:3000').axios(axios));
app.service('test_view').find();
})
.then(data => {
// do something with data
});
</script>
</head>
<body></body>
</html>
A lot of this depends on what (if anything) you're using for your front-end implementation. This sets up a minimal feathersjs/client using axios for REST, with no authentication, and calls your service (on port 3000) and gets the payload.
To do this every 5 seconds is outside the scope of feathers and up to how you build your web app.
Here is a working example of how you could change the contents of that div when you get data back from your remote call.
// Simulate your remote call... ignore this part.
const stats = {}
stats.find = () => new Promise((resolve, reject) => resolve({
data: 'here is some data ' + new Date().toLocaleTimeString('en-US')
}));
// Div you want to change.
const resultsDiv = document.getElementById('stats');
// Get the data
function getstats () {
stats.find().then(response => {
console.log('data is ', response.data);
// Update the contents of the div with your data.
resultsDiv.innerHTML = response.data;
});
}
setInterval(function() {
getstats();
}, 1000);
<html>
<head>
<title>Stats</title>
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<div id='stats'>
</div>
</body>
</html>
I'm trying to get some dynamic content to display based on UTMs in my URL. While I can call the function in the browser to get the content to display, it isn't doing so on page load. (Function works, but my timing must be off)
I've tried to change the order in which I call jQuery and my JS file, but either way it doesn't show unless I paste my function into chrome dev tools.
Here's the relevant part of the function:
// regex to find the URL param above
var dynamicContent = getParameterByName('dc');
$(document).ready(function() {
if (dynamicContent == 'fintech') {
$('#fintech').show();
}
else if (dynamicContent == 'martech') {
$('#martech').show();
}
//... excluded remaining options
else {
$('#default-content').show();
}
And the HTML:
<span id="default-content" class="dynamic-content">Tech</span>
<span id="fintech" class="dynamic-content">Fintech</span>
<span id="martech" class="dynamic-content">Martech</span>
<!-- excluded remaining options -->
And here's my header in case there's a different way I should be calling everything:
<head>
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
<link rel="stylesheet" href="assets/css/main.css" />
<noscript><link rel="stylesheet" href="assets/css/noscript.css" /></noscript>
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<script src="assets/dynamic.js" type="text/javascript"></script>
</head>
Again, as copying/pasting my code into dev tools after the page load works, how do I time it so that this function runs on page load?
Thanks.
Maybe try this:
$(window).on('load', function () {
var dynamicContent = getParameterByName('dc');
if (dynamicContent == 'fintech') {
$('#fintech').show();
}
else if (dynamicContent == 'martech') {
$('#martech').show();
}
//... excluded remaining options
else {
$('#default-content').show();
}
});
I have a lot of HTML documents in the root of my projects. Let's take a simple skeleton HTML document like so:
<!doctype html>
<html class="no-js" lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" type="image/x-icon" href="favicon.ico">
<!-- Place favicon.ico in the root directory -->
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<!--[if lt IE 8]>
<p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please upgrade your browser to improve your experience.</p>
<![endif]-->
hello
hello
hello
hello
hello
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="js/scripts.js"></script>
</body>
</html>
Now before I send all these files to the development team, I am assigned with the task of checking that there are no links which have no href, and empty href, or have an empty fragment as an href. I.e.,
Basically, there cannot be likes like so:
<a href="">
or
<a href="#">
or
<a>
I found this gulp plugin and but I have a few issues with it. Let's have a look at the gulp file first:
gulp.task("checkDev", function(callback) {
var options = {
pageUrls: [
'http://localhost:8080/Gulp-Test/index.html'
],
checkLinks: true,
summary: true
};
checkPages(console, options, callback);
});
Note that when you pass the option checkLinks: true , it's not just for the a tags , it for all of the tags mentioned on this page. The plugin doesn't have a problem if the <a> tag is empty or just has a # or is not present at all.
See what happens when I run the gulp tasks:
So what I would like instead is, if only the a links could be checked and if the <a> tag doesn't have an href or a blank value or just a #, then it should throw an error or show it in the summary report.
Lastly, see in the sample of the gulp file how I am passing the pageUrl (i.e. the pages to be checked basically) like so:
pageUrls: [
'http://localhost:8080/Gulp-Test/index.html'
],
How do I instead tell this plugin to check for all the .html files inside the Gulp-Test directory ?
So to summarize my question: how do I get this plugin to throw an error (i.e. show in the summary report) when it sees an <a> without a href or a href that is blank or has a value of # and also how do I tell this plugin to check for all .html files inside a directory.
I am assigned with the task of checking that there are no links which have no href, and empty href, or have an empty fragment as an href.
If that's all you require, you don't really need any gulp plugins. And it's doubtful that you will find something that fits your specific requirements anyway.
You can accomplish this yourself pretty easily however. All you really have to do is:
Read in all the HTML files you want to validate using gulp.src().
Pipe each file to a function of your own using through2.
Parse each file using any HTML parser you like (e.g. cheerio).
Find the bad links in the parsed HTML DOM.
Log the bad links using gutil.log() so you will know what to fix.
Maybe throw a gutil.PluginError so your build fails (this is optional).
Here's a Gulpfile that does exactly that (referencing the above points in comments):
var gulp = require('gulp');
var through = require('through2').obj;
var cheerio = require('cheerio');
var gutil = require('gulp-util');
var path = require('path');
var checkLinks = function() {
return through(function(file, enc, cb) { // [2]
var badLinks = [];
var $ = cheerio.load(file.contents.toString()); // [3]
$('a').each(function() {
var $a = $(this);
if (!$a.attr('href') || $a.attr('href') == '#') { // [4]
badLinks.push($.html($a));
}
});
if (badLinks.length > 0) {
var filePath = path.relative(file.cwd, file.path);
badLinks.forEach(function(badLink) {
gutil.log(gutil.colors.red(filePath + ': ' + badLink)); // [5]
});
throw new gutil.PluginError( 'checkLinks',
badLinks.length + ' bad links in ' + filePath); // [6]
}
cb();
});
}
gulp.task('checkLinks', function() {
gulp.src('Gulp-Test/**/*.html') // [1]
.pipe(checkLinks());
});
Running gulp checkLinks with a Gulp-Test/index.html like so ...
<html>
<head><title>Test</title></head>
<body>
<a>no href</a>
empty href
empty fragment
non-empty fragment
link
</body>
</html>
... results in the following output:
[20:01:08] Using gulpfile ~/example/gulpfile.js
[20:01:08] Starting 'checkLinks'...
[20:01:08] Finished 'checkLinks' after 21 ms
[20:01:08] Gulp-Test/index.html: <a>no href</a>
[20:01:08] Gulp-Test/index.html: empty href
[20:01:08] Gulp-Test/index.html: empty fragment
/home/sven/example/gulpfile.js:22
throw new gutil.PluginError( 'checkLinks',
^
Error: 3 bad links in Gulp-Test/index.html
var gulp = require('gulp');
var jsdom= require('jsdom').jsdom;
var fs=require('fs');
var colors= require('colors');
colors.setTheme({
error:"red",
file:"blue",
info:"green",
warn:"yellow"
});
gulp.task('checkLinks',function() {
fs.readdir('.',function(err, files){
if(err)
throw err;
var htmlFiles=files.filter(function(c,i,a){
return c.substring(c.lastIndexOf('.')+1)==="html";
});
htmlFiles.forEach(function(c,i,a){
fs.readFile(c,function(fileReadErr,data){
if(fileReadErr)
throw fileReadErr;
var doc= jsdom(data);
var window= doc.defaultView;
var $=require('jquery')(window);
var aTags=$('a').toArray();
var k=0;
console.log(("\n\n************************Checking File "+c+"***************************").info);
for(var i=0; i<aTags.length; i++){
if(!(aTags[i].hasAttribute("href")) || aTags[i].getAttribute("href")==="" || aTags[i].getAttribute("href")==="#" ) {
k++;
console.log("BAD LINK ".error+aTags[i].outerHTML.info+" IN FILE "+c.file);
}
}
console.log(("BAD-LINKS COUNT IN " +c+" is "+k).bgRed.white);
window.close();
});
});
});
});
output:
I'm trying to run this grid extention in DW CS5. I'm a front end person so debugging other people's code isn't my thing. So when I try set the grid precepts I get this error:
while executing inspectSection in dmx960 grid, js error occurred.
Here is the code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Barefoot Development Group</title>
<link href="CSS/Style.css" rel="stylesheet" type="text/css">
<link href="CSS/text.css" rel="stylesheet" type="text/css">
<link href="CSS/reset.css" rel="stylesheet" type="text/css">
</head>
<body>
<!------start container------->
<div id = "container" class ="container_16"></div>
<div id = "social_search" class = "grid_16"></div>
<div id = "social_links" class = "grid_1 alpha"></div>
<!------Main container-------->
<!------Header start---------->
<!------Social Links---------->
<!-------End social links------>
<!----start Social icons -------->
<!----end social icons----->
</body>
</html>
I tried deleting the cache in Config folder and reinstalling the extension. Didn't work. I checked the log files and found this:
JS Error: theElem.getAttribute is not a function filename:
C:\Users\cvr\AppData\Roaming\Adobe\Dreamweaver
CS5\en_US\Configuration\Shared\DMXzone\960 Grid\dmx960grid_lib.js
lineno: 598
So I went to the JS file and here is what I found in this expression block:
function getGridClassNum(theElem) {
if (!theElem) return 0;
var cls = theElem.getAttribute("class");
if (!cls) return 0;
if (cls == 'clearfix') {
//Try to read the parent
var parent = getGridElement(theElem.parentNode);
if (parent && parent.nodeType === Node.ELEMENT_NODE) {
return getGridClassNum(parent);
}
} else {
var numMatch = cls.match(new RegExp("\\b(grid|container)_(\\d+)\\b"));
if (numMatch && numMatch.length > 1) {
return parseFloat(numMatch[2]);
// //decrease with prefix and suffix
// - getGridClassNameNum(theElem, 'prefix')
// - getGridClassNameNum(theElem, 'suffix');
}
}
return 0;
}
I don't see anything particularly amiss here. But perhaps a more expert debugger can tell me if there is something going on here. Here is what confuses me - I was looking for the function inspectSection but I couldn't find it. I'm left scratching my head here.
Could this be a problem of including the script directly into the html doc?
Thanks!