Header script causing alert - jscript

When loading the page I get a alert box with unidentified in, when remove this bit code it goes. I need this as it makes the menu work.
Going in a bit blind on this so wasn't sure what it doesn't like, I suppose I should be asking what does this actually mean?
<script type="text/javascript">
var loadEvents = new Array();
function addInitFunction(func) { loadEvents.push( { 'func':func, 'seq':-1 } ); }
function addLoadEvent(func, seq) { loadEvents.push( { 'func':func, 'seq':seq } ); }
var linkver="-65";
var IP="";
var proto="https:";
var def_proto="http:";
</script>
Narrowed it down to this line
function addInitFunction(func) { loadEvents.push( { 'func':func, 'seq':-1 }); }
I've also found what I think is the function with the issue
<script type="text/javascript">
// Move responsive divs
function homeRespChange(from, too, source) {
respMoveContent('respHeaderLogin', { 'default':'respMove_HeaderLogin_default', 'phone':'respMove_HeaderLogin_phone' });
}
function homeInit() {
responsiveKick();
}
addInitFunction('homeInit');
addInitFunction('menuFixup');
addInitFunction('setWallp');
addInitFunction('tidyFunc');
addInitFunction('moveBasket');
addInitFunction('loginMenu');
function mess() {
alertX('EUCookieMessage_Holder');
}
//addLoadEvent(mess);
</script>

Related

chrome.devtools.inspectedWindow.eval - frameURL

I am trying to get the selected element to the sidebar pane in my chrome extension.
It's working fine if the page has no frames when the element is in the frame, it's not working.
As per the document I have to pass the frameURL, but how do I get the frame or Iframe URL?
Thank you.
Note: This issue is duplicate that was opened in 3 years ago, but still no solution there, so re-opening it again.
In devtools.js
chrome.devtools.panels.elements.createSidebarPane(name, (panel) => {
// listen for the elements changes
function updatePanel() {
chrome.devtools.inspectedWindow.eval("parseDOM($0)", {
frameURL: // how to pass dynamic
useContentScriptContext: true
}, (result, exceptipon) => {
if (result) {
console.log(result)
}
if (exceptipon) {
console.log(exceptipon)
}
});
}
chrome.devtools.panels.elements.onSelectionChanged.addListener(updatePanel);
});
I ran into this as well. I ended up needing to add a content_script on each page/iframe and a background page to help pass messages between devtools and content scripts.
The key bit is that in the devtools page, we should ask the content_scripts to send back what their current url is. For every content script that was registered, we can then call chrome.devtools.inspectedWindow.eval("setSelectedElement($0)", { useContentScriptContext: true, frameURL: msg.iframe } );
Or in full:
chrome.devtools.panels.elements.createSidebarPane( "example", function( sidebar ) {
const port = chrome.extension.connect({ name: "example-name" });
// announce to content scripts that they should message back with their frame urls
port.postMessage( 'SIDEBAR_INIT' );
port.onMessage.addListener(function ( msg) {
if ( msg.iframe ) {
// register with the correct frame url
chrome.devtools.panels.elements.onSelectionChanged.addListener(
() => {
chrome.devtools.inspectedWindow.eval("setSelectedElement($0)", { useContentScriptContext: true, frameURL: msg.iframe } );
}
);
} else {
// otherwise assume other messages from content scripts should update the sidebar
sidebar.setObject( msg );
}
} );
}
);
Then in the content_script, we should only process the event if we notice that the last selected element ($0) is different, since each frame on the page will also handle this.
let lastElement;
function setSelectedElement( element ) {
// if the selected element is the same, let handlers in other iframe contexts handle it instead.
if ( element !== lastElement ) {
lastElement = element;
// Pass back the object we'd like to set on the sidebar
chrome.extension.sendMessage( nextSidebarObject( element ) );
}
}
There's a bit of setup, including manifest changes, so see this PR for a full example:
https://github.com/gwwar/z-context/pull/21
You can found url of the frame this way:
document.querySelectorAll('iframe')[0].src
Assuming there is at lease one iframe.
Please note, you cannot use useContentScriptContext: true, as it will make the script execute as a context page (per documentation) and it will be in a separate sandboxed environment.
I had a slightly different problem, but it might be helpful for your case too, I was dynamically inserting an iframe to a page, and then tried to eval a script in it. Here the code that worked:
let win = chrome.devtools.inspectedWindow
let code = `
(function () {
let doc = window.document
let insertFrm = doc.createElement('IFRAME')
insertFrm.src = 'about:runner'
body.appendChild(insertFrm)
})()`
win.eval(code, function (result, error) {
if (error) {
console.log('Eror in insertFrame(), result:', result)
console.error(error)
} else {
let code = `
(function () {
let doc = window.document
let sc = doc.createElement('script')
sc.src = '${chrome.runtime.getURL('views/index.js')}'
doc.head.appendChild(sc)
})()`
win.eval(code, { frameURL: 'about:bela-runner' }, function (result, error) {
if (error) {
console.log('Eror in insertFrame(), result:', result)
console.error(error)
}
})
}
})

NodeJS Express app.locals are not directly accessible in function

This is a weird kind of a question but follow me along. I have a nodejs server with express application. Inside the application, I set my locals as follows:
var moment = require('moment');
app.locals.moment = moment;
The ejs is being rendered as:
exports.page = function (req, res) {
res.render('first-page');
};
Then, in my ejs, I have the following code:
<%
if (!moment) {
throw new Error('moment is not defined');
}
function formatDate(date) {
return moment(date).format();
}
%>
<p><%= formatDate(1435856054045); %></p>
The interesting that happens is that moment does not raise the exception. Thus, it is defined in the scope of ejs, just as documentation says. However, an exception is raised by ejs saying that moment is not defined at formatDate. If I change formatDate to the following, everything works.
function formatDate(date) {
return locals.moment(date).format();
}
My question is how are the functions, defined in ejs, are scoped and which context is applied to them. Does ejs apply a different context to the function than to the floating javascript? I'm assuming it does something like formatDateFunctionPointer.call(ejsScope, ...);
The problem becomes clear when you have ejs output the generated function (to which a template is compiled):
with (locals || {}) {
if (!moment) {
throw new Error('moment is not defined');
}
function formatDate(date) {
return moment(date).format();
}
...
}
The problem is that your formatDate function is hoisted to outside the with block; inside that block, moment is actually locals.moment, so your test to see if it exists works.
However, when you can formatDate, it's not run within the context of the with block, and therefore, moment doesn't exist (but locals.moment does, as you already found out).
Here's a standalone example of the problem:
var obj = { test : 123 };
with (obj) {
if (test !== 123) throw new Error('test does not equal 123');
function showTest() {
console.log('test', test);
}
showTest();
}
One way to resolve this is to use a function expression:
<%
if (typeof moment === 'undefined') {
throw new Error('moment is not defined');
}
var formatDate = function(date) {
return moment(date).format();
};
%>
<p><%= formatDate(1435856054045); %></p>
(it also fixes your test to see if moment is actually defined)
Or you can set the EJS _with option to false.

How to find out if reading dir is completed

everyone
I am working on some sort of image view application using node-webkit. I made a function to read dir inside the given location and search for the image files(*.jpg and *.png). Code I used is as follows:
app.js
var fs = require("fs");
var gui = require('nw.gui');
var win = gui.Window.get();
var directory;
var db = require('diskdb');
var path = require('path')
db = db.connect("lib/collections", ['temp']);
function chooseFile(name) {
var chooser = $(name);
scr = 0;
chooser.change(function(evt) {
directory = $(this).val();
var asdf;
console.clear();
readDir(directory);
$(this).val('').hide();
});
}
function readDir(directory){
c = 0;
console.log("reading "+directory);
if(fs.statSync(directory).isDirectory() == true){
fs.readdir(directory,function(err,files){
if (err){
console.log(err);
return;
}
var ext;
files.forEach(function(file){
console.log("Got what: "+file);
var fulls = directory+"\\"+file;
if(file.indexOf(".") != 0){
if(path.extname(fulls) == ""){
console.log("Got a directory: "+file);
if(fs.statSync(fulls).isDirectory() == true){
readDir(fulls);
}
}
else{
console.log("Got a file: "+file);
if(checkExtension(file, 'jpg,png')){
scr++;
c = saveTemp(fulls,scr,file);
}
}
}
});
if(c == 1){
loadgun();
}
});
}
}
function loadgun(){
if(db.temp.count()!=0){
for(i=1;i<=db.temp.count();i++){
var asd = db.temp.findOne({'id':i});
var theTempScript = $("#tmpl-imgholder").html();
var theTemp = Handlebars.compile(theTempScript);
$("#ContentWrapper").append(theTemp({"fulls":asd.file, "id":asd.id, "title":asd.title}));
}
}
}
saveTemp = function(file,id, title) {
var savedUser = db.temp.save({
file:file,
id:id,
title:title
});
return 1;
};
function checkExtension(str, ext) {
extArray = ext.split(',');
for(i=0; i < extArray.length; i++) {
if(str.toLowerCase().split('.').pop() == extArray[i]) {
return true;
}
}
return false;
};
$(document).ready(function(){
if(db.temp.count() != 0){
loadgun();
}
else{
$('#blah').css('display','block');
chooseFile('#blah');
}
});
index.html
<html>
.
.
.
<body>
<input type="file" nwdirectory id="blah" style="display:none"/>
<script src="js/jquery.min.js"></script>
<script src="js/app.js"></script>
<script src="js/handlebars.js"></script>
<script id="tmpl-imgholder" type="x-handlebars-template">
<div class="image-container grid__item" data-id="{{id}}" data-src="{{fulls}}">
<div class="cover" style="background:url({{fulls}})" title="{{title}}"></div>
<div class="info">
<div class="title">{{title}}</div>
</div>
<div class="clear"></div>
</div>
</script>
</body>
</html>
Here i tried to load data using loadgun function. Its hangs the node webkit window. If I could know when the readDir function terminates then i could do load the required datas.
If there is another way please do say.
Thanks in advance.
the problem with readDir is that is asynchronous function , that is why you have to provide a callback. you can however use fs.readdirSync(path) which is synchronous , and then the code flows synchronously. a psoducode may look like this :
function readDirAsynch(dir){
var files = fs.readdirSync(dir);
for (var i in files){
if (files[i] isDir){
readDirAsynch(files[i]);
} else if (myCondition){
//do somehting
}
}
}
needless to say , you know that the function is done when the next line after the function call is being executed
Quick answer:
You can use the synchrohous method fs.readdirSync(path) and everything should work just fine for you. You don't need to keep reading. https://nodejs.org/api/fs.html#fs_fs_readdirsync_path
My personal suggestion:
Since node is single threaded I would recommend you to keep using the asynchronous version but adding a callback to your method.
This means that your "readDir" method is going to be asynchronous too. You only need to add a callback parameter to your method. E.g.
readDir(dir, fnCallback) {
...
fs.readdir(directory, function(err,files){
... doing cool stuff ...
fnCallback();
});
}
If you want to read more about writing asynchronous code maybe this guide can help you.
http://callbackhell.com/
Also if you want to go further in the wonderful asynchronous world you can take a look to 'Promises' https://www.npmjs.com/package/node-promise, 'Future' https://www.npmjs.com/package/async-future, 'Async' https://www.npmjs.com/package/async and have more fun than you have ever imagined before.

Custom chrome extension not launching device list

I'm trying to launch the cast api from a chrome extension that i'm writing. When I run this same code in a regular old HTML file on my webserver, it works perfectly. It doesn't work when I use this code in the popup of my extension. The requestSession call doesn't work at all in that case and nothing seems to happen after it's called.
I believe the expected behaviour is that the google cast extension will show the device list popup. Here is my javascript and html. Most of it is copied right out of CastHelloVideo-chrome.
HTML:
<html>
<head>
<title>Popup</title>
<style>
body {
min-width:5px;
overflow-x:hidden;
}
</style>
<script type="text/javascript" src="https://www.gstatic.com/cv/js/sender/v1/cast_sender.js"></script>
</head>
<body>
<button type="button" id="castButton">Cast!</button>
</body>
<script type="text/javascript" src="popup.js"></script>
</html>
Javascript:
//Constants
var applicationID = "<App ID>";
var session;
var currentMediaSession;
///////////////////////////////////////////////////////////////////
//Chromecast API
///////////////////////////////////////////////////////////////////
if (!chrome.cast || !chrome.cast.isAvailable) {
setTimeout(initializeCastApi, 1000);
}
function loadMedia() {
if (!session) {
console.log("no session");
return;
}
var mediaInfo = new chrome.cast.media.MediaInfo('http://commondatastorage.googleapis.com/gtv-videos-bucket/big_buck_bunny_1080p.mp4');
mediaInfo.contentType = 'video/mp4';
var request = new chrome.cast.media.LoadRequest(mediaInfo);
request.autoplay = false;
request.currentTime = 0;
session.loadMedia(request,
onMediaDiscovered.bind(this, 'loadMedia'),
onMediaError);
}
/**
* callback on success for loading media
* #param {Object} e A non-null media object
*/
function onMediaDiscovered(how, mediaSession) {
console.log("new media session ID:" + mediaSession.mediaSessionId);
currentMediaSession = mediaSession;
}
/**
* callback on media loading error
* #param {Object} e A non-null media object
*/
function onMediaError(e) {
console.log("media error");
}
//////////////////////////////////////////////////////////////////
//UI
//////////////////////////////////////////////////////////////////
var castbutton = document.getElementById("castButton");
castButton.onclick=function(){
window.close();
chrome.cast.requestSession(onRequestSessionSuccess, onLaunchError);
// loadMedia();
};
//////////////////////////////////////////////////////////////////
//Helper Functions
//////////////////////////////////////////////////////////////////
function initializeCastApi() {
var sessionRequest = new chrome.cast.SessionRequest(applicationID);
var apiConfig = new chrome.cast.ApiConfig(sessionRequest,
sessionListener,
receiverListener);
chrome.cast.initialize(apiConfig, onInitSuccess, onError);
}
function sessionListener(e) {
console.log('New session ID: ' + e.sessionId);
session = e;
}
function receiverListener(e) {
console.log(e);
}
function onInitSuccess() {
console.log("init success");
}
function onError() {
console.log("error");
}
function onSuccess(message) {
console.log(message);
}
function onRequestSessionSuccess(e) {
session = e;
console.log("session created");
}
function onLaunchError(e) {
console.log(e.description);
}
I think this may be caused because I'm trying to run this out of the popup of my extension. Maybe chrome doesn't allow multiple plugins to show their (the device list is google cast's popup) popup window's at the same time? I've tried closing the popup before executing the requestSession call, but it still doesn't work. Anyone have any ideas?
Invoking requestionSession API call within a Chrome extension is not supported. That's why you cannot get a list of devices.
In any case this method call only works from a regular web page and it triggers the extension to show a pop-up of Cast devices. That's the only current way it's supposed to work.

Marionette + RequireJS: Doing a require inside ItemView.render()

I'm trying to load and render additional views async and append them to the ItemView.
Simplified code - why is $el not defined in the require() block in render() - what am I missing here? Am I not using RequireJS properly, or Marionette, or just my inexperience with javascript?
What is the recommended way of doing this? It needs to be dynamic as additional section views could be available at runtime that I don't know about yet as registered by plugins.
define(['require','marionette', 'App', 'swig', 'backbone.wreqr','text!./settings.html'],
function (require,Marionette, App,Swig, Wreqr, settingsHtml )
{
var sectionViews = ['./settingscontent/GeneralView'];
var SettingsView = Marionette.ItemView.extend(
{
template: Swig.compile(settingsHtml),
commands: new Wreqr.Commands(),
initialize: function ()
{
this.commands.addHandler('save', function (options, callback)
{
callback();
});
Marionette.ItemView.prototype.initialize.apply(this, arguments);
},
render: function()
{
Marionette.ItemView.prototype.render.call(this);
var $el = this.$el;
var self = this;
require(sectionViews, function (View)
{
$el.find('div.tab-content').append(new View(self.model).render().$el);
// $el is not defined
// self != outer this - $el is an empty div
});
return this;
}
}
return SettingsView;
})
Why are you trying to overload itemview.render?
Why not use the built in onrender event
https://github.com/marionettejs/backbone.marionette/blob/master/docs/marionette.itemview.md#render--onrender-event
from that documentation :
Backbone.Marionette.ItemView.extend({
onRender: function(){
// manipulate the `el` here. it's already
// been rendered, and is full of the view's
// HTML, ready to go.
}
});
seems easier and more typical of marionette usage
You need to bind this inside the function to the SettingsView object. Something like:
render: function()
{
Marionette.ItemView.prototype.render.call(this);
var $el = this.$el;
var self = this;
require(sectionViews, _.bind(function (View)
{
...
}, this));
return this;
}
The local variables will not be visible inside the bound function. You can use this and this.$el safely however.

Resources