Chrome extension problem with background page - javascript

I am trying to execute JavaScript code to the webpage when the user clicks the browser action. It worked very well, and when I tried to put it on the background page it messed up.
I want specific code to execute once and when the icon is clicked again, different code to run. I tried to do the following.
//Background page
<Script>
function goNow() {
var live = 2;
chrome.tabs.executeScript(null,
{code:"Code"});
}
function Shutdown(){
var live = 1;
chrome.tabs.executeScript(null,
{code:"Code"});
}
function runLive(live){
if (live==1) {goNow()}
else {Shutdown()}
}
chrome.browserAction.onClicked.addListener(runLive)
</script>
Of course that 'Code' is JavaScript code that works very well when injected into the page.

chrome.browserAction.onClicked.addListener passes a tab object to a callback function, you can't just pass you own parameter there.
Declaring a variable inside a function (by using var keyword) makes it available only inside this function.
You code should be something like this:
//global variable
var live = 1;
function goNow() {
live = 2;
chrome.tabs.executeScript(null, {code:"Code"});
}
function Shutdown(){
live = 1;
chrome.tabs.executeScript(null, {code:"Code"});
}
function runLive(tab){
if(live==1){goNow()}
else{Shutdown()}
}
chrome.browserAction.onClicked.addListener(runLive);

Related

How do you call a function to run specific code?

I'm making my website mobile-friendly and I'm loading different CSS files based on if the user is using a touch device or not. I have edited the question to instead create an alert box to simplify the question.
Please note: LoadCSS(style.css) has been changed to alert()
I want to run javascript code stored in a variable.
From my research, eval(variable) runs/executes the variable as code, but this isn't working.
The code I want to run is stored in "isTouchscreen" and "notTouchscreen".
-- isTouchscreen.js --
function ifTouchscreen(isTouchscreen, notTouchscreen) {
// isTouchscreen being alert('Touchscreen device!')
// notTouchscreen being alert('Not a touchscreen device!')
if(userIsUsingATouchScreen) {
eval(isTouchScreen)
} else {
eval(notTouchScreen);
// expecting "eval" to execute the variables as javascript commands/functions
}
}
-- index.html -- [Edited to use "alert"]
<!--alert() being commands that I want to be executed-->
ifTouchscreen("alert('Touchscreen device!')", "alert('Not a touchscreen device!')")
What I expect to happen is for the "isTouchscreen" variable to be run as javascript code if the user is using a touchscreen device, and for the "notTouchscreen" variable to be run as javascript code if the user is not using a touchscreen device.
I expect an "alert" to take place which doesn't happen.
How do you call a function in javascript with a variable/condition [function(variable/condition)] and get the function to execute said variable/condition as javascript code?
In your current code, LoadCSS(...) is getting called twice, and the values returned from those calls (probably undefined) are being passed as arguments to your function.
It's possible that something like this would work instead:
ifTouchscreen("LoadCSS('mobile-friendly.css')", "LoadCSS('normal.css')")
But what you really want to do is pass in a function as a "callback" for your code to call into.
ifTouchscreen(() => LoadCSS('mobile-friendly.css'), () => LoadCSS('normal.css'))
function ifTouchscreen(isTouchscreen, notTouchscreen) {
if(userIsUsingATouchScreen) {
isTouchScreen();
} else {
notTouchScreen();
}
}
You can load css dynamically like this:
function loadCssDynamically(href){
var head = document.getElementsByTagName('head')[0];
var link = document.createElement('link');
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = href;
link.media = 'all';
head.appendChild(link);
}
function ifTouchscreen(isTouchscreenHref, notTouchscreenHref) {
if(userIsUsingATouchScreen) {
loadCssDynamically(isTouchscreenHref)
} else {
loadCssDynamically(notTouchscreenHref);
}
}
ifTouchscreen('http://website.com/css/stylesheet1.css', 'http://website.com/css/stylesheet2.css')
What happens is that both functions get executed before the call to ifTouchScreen.
You must add quotes around it:
ifTouchscreen("LoadCSS('mobile-friendly.css')", "LoadCSS('normal.css')")
It is also possible I misunderstand and LoadCSS is actually returning javascript code as a text.

JS function always keep executing code at the start of my html

I'm new to JS, I watched some crash course on YouTube and try to do it on the same time. I'm using Visual Studio Code with an extension live server in order to see changes quickly.
In my JS code:
//SUBSCRIBE
var subscribeEmail = document.getElementById('subscribe-email');
var subscribeSubmit = document.getElementById('subsribe-link-btn');
//HEADER
var headerRootWrapper = document.getElementById("navbar-wrapper");
console.log(headerRootWrapper);
var show = document.getElementById('sidebar-wrapper');
//LOGO
var webLogo = document.getElementById('logo');
console.log(webLogo);
//MENU BAR
var menuBar = document.getElementById('menu-bar').addEventListener('click', menuSlideLeft());
console.log(menuBar);
var sideMenuId = document.getElementById('sidebar-wrapper');
//SEARCH BAR
var searchBar = document.getElementById('searchBarShow').addEventListener('click',searchStart());
// METHOD
function menuSlideLeft() {
alert("Fire");
}
From my Html file, I added the js script at the bottom (not inside the body tag) . It always execute the method menuSlideLeft() at the start without making me click the menuBar.
<script src="js/jscript.js"></script>
Remove the parentheses from your event listener, that calls the function. Instead use:
.addEventListener('click', menuSlideLeft);
You are calling function in this line
var menuBar = document.getElementById('menu-bar').addEventListener('click', menuSlideLeft());
check the part menuSlideLeft() in addEventListener function.
What you should do is
var menuBar = document.getElementById('menu-bar').addEventListener('click', menuSlideLeft);
i-e just pass the reference of the function. Don't call it. it will be called in that event
You are calling function instead of passing it as parameter.
Solution:
document.getElementById('menu-bar').addEventListener('click', menuSlideLeft);

Why must I access a global variable through window?

I have some JS in a file, and some JS on a page.
If I try to access my function via NucleusPreview, it can't be found
If I access it via window.NucleusPreview, it is found
Why is that? Am I doing something wrong, or do I need to be explicit when accessing objects in window scope when in another function?
Update: I was creating NucleusPreview inside the onReady, but moved it so I think the window scope was a red herring. The problem is that when calling it in onReady, gave it time to load the file, but when I moved it out I started calling it too early.
The JS in the the file is basically:
var NucleusPreview;
(function ($) {
NucleusPreview = function NucleusPreview(source) {
//ctor stuff
};
NucleusPreview.prototype.AdjustCaption = function AddCaption() {
//caption stuff
};
})(jQuery);
My JS on the page:
$('.nucleus-preview').each(function eachNucleusPreview(index, element) {
var jElement = $(element),
vidId = jElement.data('video-id'),
np = new NucleusPreview($(element)); //Uncaught RefError: NucleusPreview is not defined
_wq.push({
id: vidId,
onReady: function (video) {
np.AdjustCaption();
}
});
});
As long as the first bit of code you provided is executed first and none of the code is executed prior to the DOM being loaded (you can put all of this code in a document.ready() callback to ensure that is the case), you should be able to. Run this code snippet and wait a moment, you will see that it works without qualifying window.
In the example below, I've placed all the code in a document.ready() callback (although that is not required for the code to run) to ensure that you don't try to access $('.nucleus-preview') before the DOM is ready.
Additionally, doing this will keep NucleusPreview out of the global scope in the first place, which is always a good idea.
// Always make sure the DOM is fully loaded prior to scanning for DOM elements.
// This can be done by placing all of your code in a "document.ready()` callback
// function as I'm doing here or by placing the code at the end of the HTML document,
// just before the close of the body (</body>).
$(function(){
// Now NucleusPreview is scoped to this function, which keeps it out of the
// global scope and that's always good, so you don't pollute the window.
var NucleusPreview;
(function ($) {
NucleusPreview = function NucleusPreview(source) {
//ctor stuff
};
NucleusPreview.prototype.AdjustCaption = function AddCaption() {
//caption stuff
};
})(jQuery);
var _wq = []; // Added to allow code to execute
$('.nucleus-preview').each(function eachNucleusPreview(index, element) {
var jElement = $(element),
vidId = jElement.data('video-id'),
np = new NucleusPreview($(element)); // <-- Works just fine!
_wq.push({
id: vidId,
onReady: function (video) {
np.AdjustCaption();
}
});
});
});
console.log($('.nucleus-preview'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="nucleus-preview"></div>
<div class="nucleus-preview"></div>
<div class="nucleus-preview"></div>

Function is being called when page loads instead of on click event

I am trying to get this function to be called via click event, but for some reason it is being called when page loads. I am completely baffled on why my function is reacting this way.
Here is my function
var registerTab = function(panel){
var active = 'off';
if($('#'+panel).css('left') <= '0'){
$('#'+panel).animate({left: '0'});
active = 'on';
} else {
$('#'+panel).animate({left: '-380px'});
}
};
$(function() {
tabRegister.on('click', registerTab('sidePanel'));
});
The weird thing is if i call it when i remove the passed variable and hard-code the selector in it works fine which again makes no since to me. Please any help would be very helpful and save me some hair.
registerTab('sidePanel')
This call will cause the function to be called immediately. I think what you really want is this:
tabRegister.on('click', function () {
registerTab('sidePanel')
});

seperate 2 javascript file in asp.net page

i having a very weird problem now . I has separate 2 jquery js file with my aspx file.However the pageload doesn't seem like work.
Because I'm using UpdatePanel to asynchronously call a button click event in a page.
Therefore i attach my click event within the page load method
Here is the screen shoot of my js file
Here is the sample code for modalPopup.js
function pageLoad() {
//#region Search function
$("[id$=txtSearch]").keyup(function (e) {
"[id$=txtCurrentPage2]"
$("[id$=txtCurrentPage2]").val(1)
$("[id$=txtCurrentPage]").val(1)
$("[id$=hfCurrentTxt]").val(1)
var txtSearch = $("[id$=txtSearch]").val()
var pagesize = $("[id$=ddlRowPerPage]").val()
var skip = $("[id$=txtCurrentPage2]").val()
var type = $("[id$=hfGvType]").val()
sendData(txtSearch, skip, pagesize, type);
e.preventDefault();
});
//#endregion
The sample code for the ASPX.js
function pageLoad() {
$("[id$=txtCMemberID]").bind('keyup change', function (e) {
alert("hello");
e.preventDefault();
});
}
The modalPopup.js can work very smoothly, but the ASPX.js seem like doesn't work.Anyone face this problem before.? Please guide me some idea. Thanks
Offhand, I'd wager that you are loading ASPX.js first, and then loading modalPopup.js later in the page. Both files define a global function named pageLoad. As you cannot have two separate global functions that share the same name, one is redefining the other. Rename one of the functions (it doesn't have to be called pageLoad). Example as follows:
Change ASPX.js to:
function bindKeyUpChangeHandler() {
$("[id$=txtCMemberID]").bind('keyup change', function (e) {
alert("hello");
e.preventDefault();
});
}
then call bindKeyUpChangeHandler() in addition to pageLoad().
Instead of declaring like that why not use
Sys.Application.add_load(function () {
//do stuff on page load
});

Categories