Enable chrome extension without clicking - javascript

How to enable chrome extension without clicking it.
I need to perform a certain function from my extension every time i reload a page(no clicking)
is there a way to do it.
My code which contains the on click method
chrome.extension.onMessage.addListener(function(request, sender) {
if (request.action == "getSource") {
message.innerText = request.source;
}
});
function onWindowLoad() {
var message = document.querySelector('#message');
chrome.tabs.executeScript(null, {
file: "getPagesSource.js"
}, function() {
// If you try and inject into an extensions page or the webstore/NTP you'll get an error
if (chrome.extension.lastError) {
message.innerText = 'There was an error injecting script : \n' + chrome.extension.lastError.message;
}
});
}
window.onload = onWindowLoad;
and
chrome.extension.sendMessage({
action: "getSource",
source: started(document)
});

To include jQuery:
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
/*all your normal JavaScript (or include as link)*/
</script>
</head>
Using only pure JavaScript you can do this with:
window.onload = function(){/*your JavaScript code*/};
only the code within that function will be immediately executed.
In jQuery you can wrap the code you want executed upon loading of page inside of $(document).ready(function(){, e.g.
$(document).ready(function(){
/*code goes here*/
});
$(document).ready() checks for when a page is loaded enough to have functionality.

Related

Why does my 'menu hide' code not work when I place it within my external script file?

I have a /js/common.js file attached in the <head> of my webpage, and then the file for my page /about.aspx.
<script src='/js/common.js'></script>
<script src='/js/modernizr-custom.js'></script>
<script type="text/javascript" src="//code.jquery.com/jquery-1.11.0.min.js"></script>
I can hear how dumb this question is, and I do apologise, but it is annoying me as to why I can not figure it out.
This code here shows and hides the navigation:
var didScroll;
/* more variables .. */
$(window).scroll(function (event) {
didScroll = true;
});
setInterval(function () {
if (didScroll) {
hasScrolled();
didScroll = false;
}
}, 250);
function hasScrolled() {
var st = $(this).scrollTop();
/* Rest of code */
}
And my common.js file has the following structure:
// Declarations
var pageLoaded = false;
var fontsLoaded = false;
// Wrapper
function wrapperWidth() {
return parseFloat(document.getElementById("wrapper").offsetWidth);
}
// And so on..
//-----------------------
// jQuery Initialisation
//-----------------------
$(document).ready(function () {
//Set variables on page load
$(window).load(function () {
pageLoaded = true;
fontsLoaded = true;
});
});
If I place my js to hide the menu on scroll within the external .js file common.js, the javascript does not work and I don't know why?
At present, I place it right before the closing </body> tag on each page.
I wish to be able to place my javascript in one place 1) so that it can be easily found for maintenance and 2) most importantly, to speed up load time, as the more <script></script> tags one has, will slow down page load.
Can someone please explain why my 'menu hide' javascript will not work when I place within my common.js file?
Check if you called properly your common.js and jquery min.js
Call it in below given order
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.3/jquery.min.js"></script>
<script type="text/javascript" src="js/common.js"> </script>

javascript postmessage doesn't work

i have 2 sites, and i want to use javascriptpostMessage between them.
on my main site i write the following code in an emty html file :
<html>
<script>
window.addEventListener("message",listener_,false);
function listener_(event) {
console.log('ok!');
<html>
<script>
window.addEventListener("message",listener_,false);
function listener_(event) {
console.log('ok!');
//console.log(event);
//console.log(event.data);
}
</script>
</html>
and in other site that i want to call the postmessage from the i write the following code:
<script type="text/javascript">
window.onload = function() {
testfunction();
};
function testfunction(){
var childWin = window.open("http://my-main-site.com/indexjava2.html","child");
childWin = postMessage('message','*');
console.log(TipaltiIframeInfo.height);
}
</script>
but it doesn't work after a lot of tries. i mean
console.log('ok!'); or console.log(event); console.log(event.data);
doesn't trigger on console of main site,
what to do?
thanks
Aside from the fact that you've got a <script> and an <html> tag in the middle of your code for the receiving page and you're defining and adding the event listener twice, you're also not use postMessage correctly. Instead of this:
childWin = postMessage('message', '*');
...it should be this:
childWin.postMessage('message', '*');
If you want to learn more about postMessage, read this.
The other issue is that the message won't be received by the newly-opened page unless the page is opened before the message is sent. You're trying to send the message immediately after opening the new page, and the message is reaching the new page before the event listener is added. You could get around this with a setTimeout, but if the new page takes longer to load then this might also be unreliable.
// This is what NOT to do:
setTimeout(function() {
childWin.postMessage('message', '*');
}, 1000);
Instead, the better way is for the child page to tell the parent page when it's loaded. Then the parent and child can communicate reliably.
Here is the full corrected code, sending page first:
<script>
var childWin;
window.addEventListener('message', messageListener, false);
function messageListener(event) {
if(event.data == 'ready') {
childWin.postMessage('hello second page', '*');
}
}
window.onload = function() {
childWin = window.open('http://my-main-site.com/indexjava2.htm', 'child');
};
</script>
And the receiving page:
<script>
window.addEventListener('message', messageListener, false);
function messageListener(event) {
console.log(event.data);
}
window.opener.postMessage('ready','*');
</script>

Correctly using port.emit & port.on between main.js and a script attached to a tab

I'm trying to make a function in this extension that will open a tab with a given url and run a script on that tab with a given filename. The function mostly works except that I am unable to communicate between the main script and the script I ran on the new tab (I used .attach for this). I know the communication isn't working because it hasn't been printing "Contact successful, over" in the console which should be triggered via one of the .port functions which is currently commented out.
I have been going over the Mozilla tutorials for hours now. I'm pretty sure I screwed up something simple, but I can't find a good example in the tutorial that uses tabs, .port functions, and external scripts.
Addon works by:
(starting with Main)
Adding a button to the toolbar that opens a panel (DeltaLogPanel)
This panel has a button that triggers some user input processing (get-text.js) and our function of interest (Main.js>TryFA)
This function should open a new tab with the given url
Upon the loading of this tab, the function should also have a stored script (FAmeddle) run on this tab
The function needs to facilitate (or at least trigger) communication between the tab's script and the main script. This includes passing variables
These scripts are a severely cut down version of my addon, however the addon works and retains the main problem of doing the fifth step.
Main.js
var data = require("sdk/self").data;
var journal_entry = require("sdk/panel").Panel({
contentURL: data.url("DeltaLogPanel.html"),
contentScriptFile: data.url("get-text.js")
});
require("sdk/ui/button/action").ActionButton({
id: "show-panel",
label: "Show Panel",
icon: {
"16": "./icon-16.png",
"32": "./icon-32.png",
"64": "./icon-64.png"
},
onClick: handleClick
});
function handleClick(state) {
journal_entry.show();
}
journal_entry.on("show", function() {
journal_entry.port.emit("show");
});
function ShoutOut(x) {
console.log(x);
}
//this should open up a new tab and run a script on it
function TryFA(URL, SCRIPT) {
var tabs = require("sdk/tabs");
tabs.open({
url: URL,
onReady: function onReady(tab) {
console.log("the open triggered");
tab.attach({
contentScriptFile: data.url(SCRIPT)
});
/* tab.port.on("WeReadYouLoudAndClear",ShoutOut(signal)); */
//self.port tabs.port and tab.port don't work here
}
});
}
/* self.port.on("WeReadYouLoudAndClear",ShoutOut(signal)); */
//tabs.port tab.port and self.port really screw things up here
//This is what the panel button triggered
journal_entry.port.on("cargo-shipping", function (cargo) {
journal_entry.hide();
TryFA("http://www.reddit.com/","FAmeddle.js");
});
DeltaLogPanel.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style>
#MainPanel
{
width: 180px;
height:180px;
background-color: #ACA1A1;
}
</style>
</head>
<body id="MainPanel">
<div id="simpleOptions">
<textarea id="titleBox" placeholder="Title" rows="1"></textarea>
<button type="button" id="publishButton">Publish</button>
</div>
</body>
</html>
get-text.js
//This script was user for processing and passing along user input. It worked perfectly,
//so there's not much I need to show you here
var titleArea = document.getElementById("titleBox");
var finalButton = document.getElementById("publishButton");
//this defines the cargo on the button press then ships it.
finalButton.addEventListener('click', function() {
// Remove the newline.
var cargo = {
//This is the user input passed from the panel going to main
title: ""
};
cargo.title = titleArea.value.replace(/[\n\r]/g, '');
self.port.emit("cargo-shipping", cargo);
//next we reset everything Note, this doesn't erase local cargo, just the text on the panel
}, false);
self.port.on("show", function onShow() {
titleArea.focus();
});
FAmeddle.js
function myFunction() {
var x = document.getElementById("sr-header-area");
x.style.backgroundColor = "red";
var signal = "Contact successful, over";
console.log("the function ran at least");
self.port.emit("WeReadYouLoudAndClear", signal);
}
console.log("Shout out from the extra script!");
myFunction();
These are my questions:
Is there a better way to run a script on a newly opened tab like this?
How can I make .port and .on work in this? (If there is a better way to communicate between main.js and the new page script, explain that instead)
[optional query] I'm going to be running this overall function several times. So at least six different scripts for new tabs will be loaded one by one. How do I prevent this from causing performance issues?
EDIT: Solution
In Main
Instead of this:
function TryFA(URL, SCRIPT) {
var tabs = require("sdk/tabs");
tabs.open({
url: URL,
onReady: function onReady(tab) {
console.log("the open triggered");
tab.attach({
contentScriptFile: data.url(SCRIPT)
});
tab.port.on("WeReadYouLoudAndClear",ShoutOut(signal));
//This ShoutOut function doesn't work for a completely separate reason
}
});
}
use this:
function TryFA(URL, SCRIPT) {
var tabs = require("sdk/tabs");
tabs.open({
url: URL,
onReady: function onReady(tab) {
console.log("the open triggered");
worker = tab.attach({
contentScriptFile: data.url(SCRIPT)
});
worker.port.on("WeReadYouLoudAndClear",function(signal) {
console.log(signal);
worker.port.emit("Connection stable", Backback);
});
}
});
}
Edit 2: Backback is a message variable sent from another addon code. It's not that important.
tab.attach({
contentScriptFile: data.url(SCRIPT)
});
/* tab.port.on("WeReadYouLoudAndClear",ShoutOut(signal)); */
//self.port tabs.port and tab.port don't work here
tab.attach() returns a worker, which in turn has a port. The tab itself does not have a port, as you noted in your comment.
Alternatively attach also accepts a callback as onMessage option.
MDN also has code examples for worker and addon-main port usage.

JQuery and document ready firing repeatedly when loading data into a control

For some reason, document ready and all associated functions fire multiple times (usually twice, but sometimes even endlessly) ever since I've added the load function to a control within document ready (meant to load content into a DIV when the current document is already loaded).
These are the scripts I'm using in my head tag and these are included in all pages (the page loaded into another, would have the same script, which is what I suspect causing the problem):
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script src="scripts/mainscript.js"></script>
mainscript.js code:
var counter = 1;
var hasLoaded = false;
$(document).ready(function () {
if (!hasLoaded) {
hasLoaded = true;
if ($('.next-page').attr("data-loaded") == "false") {
console.log(counter + ") STARTED LOADING!");
$(this).attr("data-loaded", "true");
$('.next-page').load($('.next-page').attr("data-link"), function () {
counter++;
$(this).attr("data-loaded", "true");
console.log(counter + ") FINISHED LOADING!");
});
}
}
$('.tbDropDownBig li').click(function (e) {
$(this).parent().parent().find('input').val($(this).text());
$(this).parent().fadeOut(100);
});
});
OUTPUT from above console.log commands:
1) STARTED LOADING!
2) FINISHED LOADING!
1) STARTED LOADING!
2) FINISHED LOADING!
2) FINISHED LOADING!
Direction to detecting the problem:
The page loaded into "next-page" runs the same script, when loaded, of document load (because ALL pages have this script).
So it loads the data again. That is why I put the data-loaded attribute, but it hasn't helped.
Solved by stopping use of "ready", instead, binded "load" event to window like this:
function LoadNextPage() {
if (!hasLoaded) {
$('.next-page').load($('.next-page').attr("data-link"), function () {
$(this).attr("data-loaded", "true");
hasLoaded = true;
});
}
}
$(window).bind("load", function() {
LoadNextPage();
});

$.html renders script as content

For a project i'm dynamically loading content that consist of html and javascript. Until now i was using jquery 1.8.3 but while cleaning up i wanted to update to 1.10.1.
I've narrowed my problem down to the way i use the $.html() function on my content div.
In jquery 1.8.3:
var content = $("#content");
contentDiv.html("<script> alert('Testing'); </script>")
shows a alertbox with the content 'Testing', while in newer jquery versions the same code the string is inserted into the DOM and then the alertbox also appears. I'd wish to not have the tags shown.
context javascript:
this.loadPage = function(page, callback){
$.get(page.ViewFile, function(view){
var content = $("#content");
$("#content").html(view);
}};
The page getting loaded contains, which is stored in the variable view as a string.
<h1>New Content</h1>
<div id="newContent"></div>
<script>
function View(){
this.InitializeView = function(model){
//code
}
this.UpdateView = function (model){
//code
}
}
</script>
Seems that the browser detect the </script> (the end of script tag) that is inside of string as a real closing when we put our code in the head of page.
This is the reason why the error is thrown in the webpage (EXAMPLE):
Uncaught SyntaxError: Unexpected token ILLEGAL fiddle.jshell.net/:22
I guess that you have to move your javascript code into a separate file like main.js, for example.
Tested it locally and it works:
HTML
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.1.js"></script>
<script src="main.js"></script>
<script type="text/javascript">
setTimeout(function () {
$("body").text("Testing now from HTML: using <script>");
setTimeout(function () {
$("body").html("<script>alert('This alert will fail.')</script>");
}, 1000);
}, 2000);
</script>
</head>
<body></body>
</html>
Javascript (main.js)
$(document).ready(function () {
$("body").html("<h1>Wait one second.</h1>");
setTimeout(function () {
$("body").html("<script>alert('Tested')</script>");
}, 1000);
});
Even the text editors detect it as closing tag:
Solution
1. Create scripts from jQuery
var content = $("#content");
var script = $("<script>");
script.html("alert('Testing');");
content.append(script)
1. Use &
Basically you have to replace < with &lt, > with &gt and & with &amp, as described in this answer:
var tagsToReplace = {
'&': '&',
'<': '<',
'>': '>'
};
function replaceTag(tag) {
return tagsToReplace[tag] || tag;
}
function safe_tags_replace(str) {
return str.replace(/[&<>]/g, replaceTag);
}
For more information see this question.

Categories

Resources