Remove injected script in chrome extension - javascript

chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(
null, {file : "app.js"});
});
I am injecting a code like this to the extension on click. But I want to remove this injected code when the user clicks the extension Icon second time. How is it possible. The code Injects an html div with id "pluginHolder". I can manually remove it using the basic js code document.getElementById('pluginHolder').remove();.
How to do this process dynamically?
Thanks in advance

I think the simplest solution something like
if(document.getElementById('pluginHolder')) {
document.getElementById('pluginHolder').remove()
} else {
var pluginHolder = document.createElement('div');
document.body.appendChild(pluginHolder);
}
If you want to affect js code and not DOM.
you can use play with eventListener ,
function logMouse() {
console.log(e.x+':'+e.y);
}
// Initialize on first run to true else use old value NOT(!) ( last time injected script)
isEnable = isEnable ? !isEnable : !!isEnable;
if(isEnable) {
window.addEventListener('mousemove', logMouse);
} else {
window.removeEventListener('mousemove', logMouse);
}

Related

Script to change animation play state

If i put some script in HTML file to change the animation play state,it's works.But when i put the script in a script file,it's not working.Can anyone tell me why?
script like this:
var buttons=document.getElementsByTagName("button");
for(var i=0;i<buttons.length;i++) {
console.log(buttons.length);
buttons[i].onclick=function(e) {
document.getElementById("para")
.style.WebkitAnimationPlayState=e.target.innerHTML;
};
}
The elements may not be defined in document. Try placing the existing script within load event handler of window
function toggleAnimationPlayState() {
var buttons=document.getElementsByTagName("button");
for(var i=0;i<buttons.length;i++) {
console.log(buttons.length);
buttons[i].onclick=function(e) {
document.getElementById("para")
.style.WebkitAnimationPlayState=e.target.innerHTML;
};
}
}
window.addEventListener("load", toggleAnimationPlayState);
Your script dependens on the existing of this Button :
=document.getElementsByTagName("button");
So,
it works because the script has been running after rendering the button .
It does not work because either :
Fail to import script. (check browser's console)
OR
Import the script BEFORE rendering the button .
Solution :
follow this order .
<button>....</button>
.......
<script src="/uri/of/script.js"></script>
OR, run your code inside onload listner of window

Javascript/Jquery Boolean help: Hiding/Showing Divs

Can someone explain to me what i am doing wrong in this code?
http://jsfiddle.net/14njfqef/
var isLoggedIn = function(state){
if(state == true) {
$("#content-container").show();
$("#account2").show();
$("#account").hide();
}
else(state == false){
$("#content-container").hide();
$("#account2").hide();
$("#account").show();
}
}
onload=function() {
isLoggedIn(false);
}
On load i want the divs to hide but then when i click the button i want the divs to show?
Is the boolean function set out in the correct way?
Piece below tries to re-arrange piece at OP. onload not appear clearly defined , not addressed , though could be attached to an event , i.e.g., window.onload = onload . Wrapped blocks in jquery .ready() event . Removed js onclick markup from html , included at script element , or loaded from file at jquery .on("click") event . Added strict comparison operator === (an added =) to if / else if statements. Changed input type to button. Added if to else portion of composition (see link posted at comments by Felix Kling).
Try
$(function() {
var isLoggedIn = function(state){
if(state === true) {
$("#content-container").show();
$("#account2").show();
$("#account").hide();
}
else if(state === false){
$("#content-container").hide();
$("#account2").hide();
$("#account").show();
}
};
isLoggedIn(false);
$("input[type=button]").click(function() {
isLoggedIn(true)
})
});
jsfiddle http://jsfiddle.net/guest271314/14njfqef/3/
changed your html to
<input type="submit" value="Boolean" id="toggle"/>
rewrote your js as
// JQuery run at start effectivly
$(document).ready(function() {
function isLoggedIn(state) {
if(state == true) {
$("#content-container").show();
$("#account2").show();
$("#account").hide();
}
else {
$("#content-container").hide();
$("#account2").hide();
$("#account").show();
}
}
// JQuery attaching a click event using an anonymous function
// and hard coding your isLoggedIn to true, passing variables is a bit more complicated.
$('#toggle').click(function() {isLoggedIn(true)});
isLoggedIn(false);
})
Well there's a few things I am not sure if you are aware of so I feel there's some responsibility on my end to make sure they are mentioned. They are a number of syntactical errors in your post that are stopping this from working so instead of addressing them I feel its necessary to update your view on what JQuery you are using as well as your selector choice.
First I would add a class structure to all of the div's to target them all at once so you can save on some lines of code. In production it's always better to have less code for all of your visitors to download because even a little bit of code can get out of control after enough hits on a webpage. Having to serve it kills speed and so does having to process three separate jquery selections as opposed to one.
I would change the HTML to...
<body>
<div id='content-container' class='boxes'>
Content Container
</div>
<div id='account' class='boxes'>
account
</div>
<div id='account2' class='boxes'>
account2
</div>
<input id="validateButton" type="submit" value="Boolean">
</body>
This way you can simply target all divs with $(".boxes"); ... I wouldn't recommend getting into the habbit of using $("div");
Next I would change the JQuery to being more JQuery friendly code. Its not always useful to use an onload event from pure Javascript to handle JQuery driven functions in correct time to the loading of DOM objects. Therefore you should use $( document ).ready( handler ) to handle this load event properly just in case it causes you problems down the road. The more common shorthand of this ready event is a simple $(function() { }); wrapper.
The rest of the code can be re-arranged to this....
var isLoggedIn = false; //<--Instantiate to false, make global to window level scope
//Load event Corrected For JQuery
$(function() {
$(".boxes").hide(); //<--Hide on load
//Add A Proper Updated Click Event To Button
$("#validateButton").click(function() {
isLoggedIn = true; //<--Should include real functionality not hand coded to true
checkLoginAndRespond(); //<--Validate Login Status
});
});
function checkLoginAndRespond() {
//If Logged, Show
if(isLoggedIn) {
$(".boxes").show();
//Else Don't
} else { $(".boxes").hide(); }
} //end function
Lastly, the version. New versions of JQuery have not been released for some time and seem to not be in the making so its a safe bet to use their most recent versions as it has thousands of pages of help for its syntax and it's very stable. I would recommend anything in the 2.0 or higher series JQuery.
I am assuming you have JQuery library loaded. Try
if (state) {
$("#content-container").show();
$("#account2").show();
$("#account").hide();
}
else{
$("#content-container").hide();
$("#account2").hide();
$("#account").show();
}
to solve your problem.

Using onKeyDown Chrome App

I have a question for you guys I'm not 100% sure how to implement this
chrome.app.window.onKeyDown = function(e) {
if (e.keyCode == 27 /* ESC */) { e.preventDefault(); }
};
I have my manifest going to my main.js file and in that file is
chrome.app.runtime.onLaunched.addListener(function() {
chrome.app.window.create('browser.html', {
state: "fullscreen"
});
});
How do I add that OnKeyDown to my main.js to get it to work? Or do I need to put that function into another file? Any help would be appreciated
Try this:
chrome.app.runtime.onLaunched.addListener(function() {
chrome.app.window.create(
'browser.html',
{state: "fullscreen"},
function(win) {
win.contentWindow.onKeyDown = function(e) ...
}
);
});
Alternatively, you can link another script from your HTML:
browser.html:
...
<script src="xyz.js"></script>
And reference the same window object from xyz.js as:
chrome.app.window.current().onKeyDown = ...
I don't see chrome.app.window.onKeyDown in the Chrome API documentation.
The DOM window is available as win.contentWindow (not as win), assuming win is the argument to the chrome.app.window.create callback function. That's the window to which you should add a listener, using the addListener function. I'm not sure that onKeyDown as a property (...onKeyDown = function...) is defined.
It makes no difference whether you add the listener in the background.js page or the page referenced from the HTML file. I would think that the latter would be better, as a keydown event is only relevant to the user interface, not the background page. Also, whatever actions you take when a key is pressed probably are for the app page, not the background page.

Removing Yet not Deleting an Element/Variable from an HTML Document

I am testing out with a different way of menus. My code is the following:
JavaScript
var hubOpen = 0;
var test = "test";
$(document).ready(function(){
$('#hub').click(function(){
if(hubOpen == 0){
$('#hub').append(test);
hubOpen = 1;
} else {
//code for taking "test" out here
hubOpen = 0;
};
});
});
HTML
<body>
<p id="hub">Hub</p>
</body>
If you'd like, here's a jsFiddle here. The code is to make sure that when the id "hub" is clicked, "test" appears. When hub is clicked again, "test" disappears. The code, when run, opens test, doesn't let you click it again, but it doesn't delete "test" (as there is no code for it).
My question: How would I delete the variable "test" from the document but not to delete the variable forever, as I would need to use it later? Would the jQuery method
.replace();
work?
Thanks in advance!
To remove all the contents of an element, jQuery offers .empty():
$('#hub').empty();
The variable is completely separate from the element, so no problems there. If you wanted to restore the original text, just use .text():
$('#hub').text('Hub');
Updated fiddle
You can do something like this:
$(document).ready(function(){
$('#hub').click(function(){
$(this).text() == 'Hub' ? $(this).html('text') : $(this).html('Hub');
});
});
On click if the text is 'Hub' change it to 'text' else change it again to 'Hub'.

Using DomNodeInserted to rewrite HTML before it finishes loading

I feel like this will probably be immediately obvious to any of the non-amateurs out there, but I've been stumped on this for days.
I am writing a Chrome Extension that executes a script at document start. I want to rewrite the HTML of specific DIVs as they load, but before they are displayed to the user (so the user doesn't see the site's HTML before it is unceremoniously replaced by my custom HTML). The method I am trying to use looks like this.
addEventListener('DOMNodeInserted', function(event){
if(event.relatedNode.innerHTML.indexOf("contentArea")>-1){
writeContentArea();
}
}, false);
function writeContentArea(){
var divtowrite = document.getElementById('contentArea');
include(divtowrite,"contentArea.html"); //my AJAX include function
}
Now, the problem is, when the page loads and the JS executes, the div will still load before it is replaced. The weird thing is when I try this with a different div, like a sidebar, it works as expected; i.e., the div is replaced before it is displayed to the user. I can't figure out why it works for some divs and not for others.
I don't know if this is relevant, but on the Chrome side I have:
chrome.tabs.getSelected(null, function(tab) {
if(tab.url.indexOf("search.php") > -1){
chrome.tabs.executeScript(null,
{file: "fhrun.js", allFrames: false, runAt: "document_start"}
);
}
});
Any ideas of why this isn't working, or a better method that I should be using? Thanks!!
Not sure if this is the approach you are looking for, but have you considered injecting CSS to hide the content area on initial load and setting it to visible in javascript once you modified the content?
The CSS file would read like this:
#contentArea { display:none; }
or
#contentArea { visibility:hidden; }
and you would inject it using:
chrome.tabs.insertCSS(null,
{file: "youfile.css", allFrames: false, runAt: "document_start"});
Then modify your content changing function to be:
function writeContentArea(){
var divtowrite = document.getElementById('contentArea');
include(divtowrite,"contentArea.html"); //my AJAX include function
divtowrite.style.display = 'block';
}

Categories

Resources