I am writing a Chrome extension that needs to be able to add code into the web page it is viewing. Right now in my background page I have:
chrome.tabs.onUpdated.addListener(function(tabId, info) {
if (info.status=="complete") {
chrome.tabs.executeScript(null, {file: "injectme.js"})
}
})
and the injected script injectme.js which contains a function that looks like this:
function() {
if (!document.getElementById('searchforme')) {
x=document.createElement('script')
x.setAttribute('src','https://sites.google.com/site/searchformechrome/files/theinjectedcode.js')
x.setAttribute('id','searchforme')
document.appendChild(x)
alert('it is finished')
} else {
alert('so close')
}
}
My question is how do I call this function the moment it loads so it can insert the script into a web page?
If I understood you :)
All you need to do is to warp you current function inside something like:
(function () {
// your code
if (!document.getElementById('searchforme')) {
x=document.createElement('script')
x.setAttribute('src','https://sites.google.com/site/searchformechrome/files/theinjectedcode.js')
x.setAttribute('id','searchforme')
document.appendChild(x)
alert('it is finished')
} else {
alert('so close')
}
}());
so it will be an 'immediate invocation' function.
Related
I really can't figure out how to do it. I need to call somefunc() from file.js file on page load.
My file.js contains:
function somefunc() {
pc.somefunc(gotLocalDescription,
function(error) {
console.log(error)
}, {
'mandatory': {
'OfferToReceiveAudio': true,
'OfferToReceiveVideo': true
}
});
}
// Socket.io
var socket = io.connect('', {
port: 1234
});
function sendCall(call) {
socket.emit('call', call);
}
socket.on('call', function(call) {
if (call.type === 'offer') {
pc.setRemoteDescription(new SessionDescription(call));
createAnswer();
} else if (call.type === 'answer') {
console.log('10--if call type is answer');
pc.setRemoteDescription(new SessionDescription(call));
} else if (call.type === 'candidate') {
var candidate = new IceCandidate({
sdpMLineIndex: call.label,
candidate: call.candidate
});
pc.addIceCandidate(candidate);
}
});
consider using
Trigger
instead
You can simple call the function which is in another file.
Have created a plunker.Also note it has a seperate file file.js. If you using name spacing please take care of that.
Click Me
WORKING COPY
You can use this:
click
But first you must include file.js in you html
<script type="text/javascript" src="file.js">
Using window.onload (pure javascript), you can call your somefunc() of file.js on page load, as following:
function somefunc() {
alert('somefunc() of file.js called!');
/*
* Your logic goes here.
*/
}
window.onload = somefunc();
DEMO
While, if you want to use jQuery, then include jquery source first and then your custom script file containing your method and DOM ready call, as following:
function somefunc() {
alert('somefunc() of file.js called!');
/*
* Your logic goes here.
*/
}
jQuery(document).ready(function(){
somefunc();
});
// OR
jQuery(function({
somefunc();
});
First make sure you have included your file.js to head of your html and the location to file is correct.
I'm using NightwatchJS with NodeJS: http://nightwatchjs.org/api
I have a modal dialog, which may or may not appear. It has a #close_button that needs to be clicked (if the modal does appear) to continue.
I set the abortOnFailure parameter of waitForElementPresent to false so the script continues if the modal does not appear. However I can't get it to work.
Any suggestions?
module.exports = {
"Test" : function (browser) {
browser
.url("http://domain.com/")
.waitForElementPresent('#close_button', 5000, false, function() {
this.click('#close_button')
})
.setValue('#username', 'test#email.com')
//more code here
.end(); //does end() go here or inside .waitForElementPresent() above?
}
}
abortOnFailure works fine, however waitForElementPresent has a bug now in which the callback you passed it's not called in the correct context. That will be fixed.
In the mean time you can write your test like this, with placing the click outside, which is the same thing and looks cleaner:
module.exports = {
"Test" : function (browser) {
browser
.url("http://domain.com/")
.waitForElementPresent('#close_button', 5000, false)
.click('#close_button')
.setValue('#username', 'test#email.com')
//more code here
.end(); // end() goes here
}
}
I ran into something similar, I was waiting for an iframe to be present. I created a function to actually close it:
pageObject function:
Home.prototype.closeIframe = function(browser) {
var self = this;
console.log('Checking for iframe');
this.browser
.isVisible(iframeSelectors.iframe, function(result) {
if (result.value === true) {
self.browser
.log('iframe visible')
.frame(iframeSelectors.name)
.waitForElementVisible(iframeSelectors.closeLink)
.click(iframeSelectors.closeLink)
.assert.elementNotPresent(iframeSelectors.iframe)
.frame(null)
.pause(2000); //allow for proper frame switching
} else {
console.log('iframe is not visible');
}
});
return this;
In my test I wait for the page to fully load before executing the above function.
Using jQuery the following would log that the app had loaded once the DOM and all assets had been downloaded by the browser:
$(window).load(function() {
console.log('app loaded');
});
However I don't want this check to happen until after some other things have run.
So for example:
function checkLoaded()
{
$(window).load(function() {
console.log('app loaded');
});
}
So let's say I call this function after a bunch of other functions.
The problem is, because $(window).load(function() is an event listener, when I call the checkLoaded() function the event won't ALWAYS run (because it MAY have already been fired because everything has downloaded BEFORE the checkLoaded() function has run).
Any ideas on how I can do this?
I tried this:
function checkLoaded()
{
if(loaded)
{
console.log('app loaded');
}
else
{
checkLoaded(); // keep checking until the loaded becomes true
}
}
$(window).load(function(){
loaded = true;
});
But the problem here is that the checkLoaded function COULD get called hundreds of times in a few seconds and isn't a nice way of handling this.
UPDATE: The function is called using checkLoaded(); Just so everyone knows I am calling the function!
UPDATE 2:
The plan is essentially this:
function init() {
start();
}();
function start() {
// Show Preloader... and other stuff
/// Once all logic has finished call checkLoaded
checkLoaded();
}
function checkLoaded() {
if(loaded) {
show();
}
}
function show() {
... // show app
}
So I should be able to know if the status of loaded is true, but keep checking until it becomes true as it may be true or false when I get to the checking stage.
You run it either on window load or if it's already done using such kind of code:
function onLoad(loading, loaded) {
if (document.readyState === 'complete') {
return loaded();
}
loading();
if (window.addEventListener) {
window.addEventListener('load', loaded, false);
} else if (window.attachEvent) {
window.attachEvent('onload', loaded);
}
}
onLoad(function() {
console.log('I am waiting for the page to be loaded');
}, function() {
console.log('The page is loaded');
});
var loaded=false;
$(window).load(function() {
loaded=true;
});
function checkLoaded()
{
// do something if loaded===true
}
Try this
function checkLoaded()
{
$(window).load(function() {
console.log('app loaded');
});
}
checkLoaded();
you want to make checkLoaded block and thats a bad idea:
javascript has no threads and blocking like that will just burn CPU while potentially blocking the whole script.
don't wait like you do for loaded to be to true. use the eventhandler as it is meant to be used.
maybe give checkLoaded a parameter to a function you want called:
function checkLoaded(continueWhenLoaded) {
$(window).load(function() {
continueWhenLoaded();
});
}
Have you looked into a solution involving jQuery's .promise() and .done()? Look at some of the examples in the documentation, it might be what you are looking for.
I want to run a content script to identify the first image that links somewhere and return the link to the background script. But I can't pass any messages between them, and I don't know why. Much of the code is comment, I'm trying to simply test if the content script is executing by telling it to change the first header to "test" (since the only thing I can do without messages is change a page's HTML and CSS). The code follows:
EDIT: full updated code
Background script:
chrome.browserAction.onClicked.addListener(function () {
chrome.tabs.query({active:true, currentWindow:true}, function(tabs)
{
chrome.tabs.executeScript(tabs[0].id, {file:"content.js"}, function ()
{
console.log("sending first time");
console.log(tabs[0].id);
chrome.tabs.sendMessage(tabs[0].id,{test: "test"}, function (response)
{
if (undefined == response)
{
console.log ("first one didn't work");
chrome.tabs.sendMessage(tabs[0].id, {test: "test"}, function (response)
{
console.log(response.test);
});
}
});
});
});
});
Content Script:
chrome.runtime.onMessage.addListener( function (msg, sender, sendResponse)
{
/*var test1 = document.getElementsByTagName("h1")[0];
test1.innerHTML="test";*/
sendReponse({test: "123"});
/*var parentList =document.getElementsByTagName("a");
var link = "";
var child;
for (var i=2; i<parentList.length;i++)
{
child=parentList[i].firstChild;
if ("IMG"==child.nodeName)
{
link=parentList[i].href;
break;
}
}
teste1.innerHTML=link;
var answer = new Object();
Answer.link = link;
teste1.innerHTML=answer.link;
sendResponse({messager:answer});*/
});
I was testing the extension at the extension page itself. But it seems you can't inject javascript in it (probably because it is a browser's settings page). It worked nicely on other pages.
I'm just starting out with javascript. My chrome extension is currently functioning but I'd like to add more functionality to it. When clicked, it runs this in background.html:
chrome.browserAction.onClicked.addListener(function (tab) {
chrome.tabs.executeScript(null, { file: "hello.js" });
});
If I wanted to have the button toggle between hello.js script and goodbye.js; how would I accomplish this?
if (localStorage["toggle"] && localStorage["toggle"]=="hello"){
alert("Good Bye");
localStorage["toggle"]="goodbye";
} else {
alert("Hello");
localStorage["toggle"]="hello";
}
Thats how Id do it in the popup of a Browser Actions html/js.
If your doing it from the background then just change the localStorage to a variable.
var toggle;
chrome.browserAction.onClicked.addListener(function (tab) {
if (toggle=="hello"){
chrome.tabs.executeScript(null, { file: "goodbye.js" });;
toggle="goodbye";
} else {
chrome.tabs.executeScript(null, { file: "hello.js" });
toggle="hello";
}
});