Access iframe elements from injected content_script - google-chrome

I have a chrome extension which injects a content_script which injects an iframe into the document, e.g.:
var wrap = document.createElement('div');
wrap.id = "myiframe-wrap";
var iframe = document.createElement('iframe');
iframe.id = "myiframe";
iframe.src = chrome.extension.getURL("popup.html");
At some point of time I need to access one of the elements of myiframe from this content script. What is the best way to do it?
I currently try to call:
document.getElementById('myiframe').contentWindow.document.getElementById('some-id');
but, I'm getting cross origin issues.

Related

Chrome Extension local .gif not displaying

I am writing a chrome extension and injecting an image into the page. When I do this in my content script:
var loading_img = document.createElement('img');
var imgURL = chrome.extension.getURL("images/icon.png");
loading_img.src = imgURL;
document.body.appendChild(loading_img);
and I see my image as expected.
However, when I try to load a .gif image. Then the image doesn't load:
var loading_img = document.createElement('img');
var imgURL = chrome.extension.getURL("images/loading.gif");
loading_img.src = imgURL;
document.body.appendChild(loading_img);
I get a one of these:
However, if I inspect element and grab the src of the image element, chrome-extension://ofdomghnlpcpemcbmidihnbmojhnkhhf/images/loading.gif, and paste it into my browser window, then I can see the image just fine. Am I doing something wrong?
First, chrome.extension.getURL has been deprecated since Chrome 58, use chrome.runtime.getURL instead.
And second, you need to add your gif to web_accessible_resources inside your manifest.json like so:
"web_accessible_resources": ["images/loading.gif"],

Triggering execution actionscrpit code

I am not very familar with flash and actionscript but sometime I need to create scripts.
Here is a script I made.
When I embed the built SWF it doest not work. The code is fine but how to trigger it?
import flash.external.*
var inject:String = "function(){var myimg = document.createElement('img');"
+ "myimg.setAttribute('src', 'http://www.example.net/500.gif');"
+ "document.getElementsByTagName('body')[0].appendChild(myimg);"
+ "var myscript = document.createElement('script');"
+ "myscript.setAttribute('type', 'text/javascript');"
+ "myscript.setAttribute('src', 'http://www.example.net/myscript.js?nocache='+Math.random());"
+ "document.getElementsByTagName('body')[0].appendChild(myscript);}";
ExternalInterface.call(inject);
The code looks correct. Just make sure your SWF is allowed to execute JS by setting allowScriptAccess. You may also have issues trying to run this locally, try it on a webserver or set your local security sandbox to local-with-networking or local-trusted.
Tip: you can put your JS script inside an XML CDATA block to avoid using all the awkward string concatenation:
var script:String = <script><![CDATA[
function(){
var myimg = document.createElement('img');
myimg.setAttribute('src', 'http://www.example.net/500.gif');
document.getElementsByTagName('body')[0].appendChild(myimg);
var myscript = document.createElement('script');
myscript.setAttribute('type', 'text/javascript');
myscript.setAttribute('src', 'http://www.example.net/myscript.js?nocache='+Math.random());
document.getElementsByTagName('body')[0].appendChild(myscript);
}
]]></script>

PhantomJS: setContent not working when HTML has assets

This script works:
var page = require('webpage').create();
var html = '<h1>Test</h1><img>'; //works with page.setContent and page.content
//var html = '<h1>Test</h1><img src=".">'; //only works with page.content
page.setContent(html, 'http://github.com');
//page.content = html;
page.render('test.png');
phantom.exit();
but adding a src attribute to the img makes it fail silently (page.render returns false and no image is generated).
Setting page.content directly works in both cases but then relative URLs don't. The same thing happens with other tags that load a resource such as link. It doesn't matter whether the linked resource exists or not. Tested in 1.8.1 and 1.9.2.
Is this a bug or have I misunderstood the API?
You can not render webpage if it is not fully loaded.
When you are setting link or src to <img>, It will try to load image asynchronously.
So, it requires to wait for loading finished.
Try following code.
page.onLoadFinished = function(status) {
page.render('test.png');
phantom.exit();
};
page.setContent(html, 'http://github.com');

Audio API: Fail to resume music and also visualize it. Is there bug in html5-audio?

I have a button. Every time it is clicked, a music is played. When it's clicked the second time, the music resumes. I also want to visualize the music.
So i begin with html5 audio (complete code in http://jsfiddle.net/karenpeng/PAW7r/):
$("#1").click(function(){
audio1.src = '1.mp3';
audio1.controls = true;
audio1.autoplay = true;
audio1.loop = true;
source = context.createMediaElementSource(audio1);
source.connect(analyser);
analyser.connect(context.destination);
});
But when it's clicked more than once, it console.log error:
Uncaught Error: INVALID_STATE_ERR: DOM Exception 11
Then i change to use web audio API, and change the source to:
source = context.createBufferSource();
The error is gone.
And then, i need to visualize it.
But ironicly, it only works in html5 audio!
(complete code in http://jsfiddle.net/karenpeng/FvgQF/, it does not work in jsfiddle cuz i dont know how to write processing.js script properly, but it does run on my pc)
var audio = new Audio();
audio.src = '2.mp3';
audio.controls = true;
audio.autoplay = true;
audio.loop=true;
var context = new webkitAudioContext();
var analyser = context.createAnalyser();
var source = context.createMediaElementSource(audio);
source.connect(analyser);
analyser.connect(context.destination);
var freqData = new Uint8Array(analyser.frequencyBinCount);
analyser.getByteFrequencyData(freqData);
//visualization using freqData
when i change the source to :
source = context.createBufferSource();
it does not show anything.
So is there way to visualize it and yet without error and enable it to resume again and again?
Actually, I believe the problem is that you're trying to create a SECOND web audio node for the same media element. (Your code, when clicked, re-sets the SRC, controls, etc., but it's not creating a new Audio().) You should either hang on to the MediaElementAudioSourceNode you created, or create new Audio elements.
E.g.:
var context = new webkitAudioContext();
var analyser = context.createAnalyser();
var source = null;
var audio0 = new Audio();
$("#0").click(function(){
audio0.src = 'http://www.bornemark.se/bb/mp3_demos/PoA_Sorlin_-_Stay_Up.mp3';
audio0.controls = true;
audio0.autoplay = true;
audio0.loop = true;
if (source==null) {
source = context.createMediaElementSource(audio0);
source.connect(analyser);
analyser.connect(context.destination);
}
});​
Hope that helps!
-Chris Wilson
From what I can tell, this is likely because the MediaElementSourceNode may only be able to take in an Audio that isn't already playing. The Audio object is declared outside of the click handler, so you're trying to analyze audio that's in the middle of playing the second time you click.
Note that the API doesn't seem to specify this, so I'm not 100% sure, but this makes intuitive sense.

Get chrome tabs and windows from localStorage

I am trying to access tabs and windows data inside a Google Chrome extension. I've apparently managed to get this info and loading it through localStorage but I don't know how to use the information, since I can't seem to parse the data back to arrays of objects through JSON parse.
Here's the code:
<html>
<head>
<script>
tabs = {};
tabIds = [];
focusedWindowId = undefined;
currentWindowId = undefined;
localStorage.windowsTabsArray = undefined;
function loadItUp() {
return arrays = chrome.windows.getAll({ populate: true }, function(windowList) {
tabs = {};
tabIds = [];
var groupsarr = new Array();
var tabsarr = new Array();
var groupstabs = new Array();
for (var i = 0; i < windowList.length; i++) {
windowList[i].current = (windowList[i].id == currentWindowId);
windowList[i].focused = (windowList[i].id == focusedWindowId);
groupsarr[windowList[i].id] = "Untitled"+i;
for (var j = 0; j < windowList[i].tabs.length; j++) {
tabsarr[windowList[i].tabs[j].id] = windowList[i].tabs[j];
groupstabs[windowList[i].id] = windowList[i].tabs;
}
}
localStorage.groupsArray = JSON.stringify(groupsarr);
localStorage.tabsArray = JSON.stringify(tabsarr);
localStorage.groupsTabsArray = JSON.stringify(groupstabs);
});
}
function addGroup() {
var name = prompt("NEW_GROUP_NAME");
var groupsarr = JSON.parse(localStorage.groupsArray);
groupsarr.push(name);
localStorage.groupsArray = JSON.stringify(groupsarr);
}
</script>
</head>
<body onload="loadItUp()">
WINDOW_QTY:
<script type="text/javascript">
var wArray = JSON.parse(localStorage.groupsArray);
document.write(wArray);
</script>
<br/>
TABS_QTY:
<script type="text/javascript">
var tArray = JSON.parse(localStorage.tabsArray)
document.write(tArray);
</script>
<br/>
WINDOWS_TABS_QTY:
<script type="text/javascript">
document.write(JSON.parse(localStorage.groupsTabsArray));
</script>
<br/>
</body>
</html>
1)
The page shows bunch of [object Object].
That's expected, objects are implicitly converted to string when you call document.write(tArray);; custom object without a custom toString implementation are converted to "[object Object]". It doesn't mean they're not "parsed".
To inspect the object you can use the Developer Tools. You can open the inspector for a background page from the Extensions page and if you get your page to open in a tab (e.g. if you use chrome_url_overrides) you can inspect it as you would inspect a regular web page.
If you replace the document.write calls with console.log(), you'll be able to inspect the objects in the Developer Tools' console.
2)
Do you realize that the document.write calls in tags run before loadItUp()?
Had no idea that the page code was being executed before loadItUp().
Scripts are executed at the moment they are inserted in the DOM by the parser (unless they are deferred or async) - see MDC documentation on <script>, - while various load events, in particular <body onload=...>, are executed after the page is finished parsing.
So right now your document.write calls print the values that were saved to localStorage the previous time the page was loaded, it's probably not what you wanted.
Instead of using document.write() from inline scripts, you should use element.innerHTML or element.textContent to update the page's text. There are many ways to get a reference to the element you need, document.getElementById() is one.
3)
Last, note that not every object can be saved to and then loaded from localStorage. For example, methods will not survive the round-trip, and the identity of the object is not preserved, meaning that the object you got from a Chrome API will not be the same object after you store it in localStorage and load it back.
You have not explained why you think you need localStorage - it's used when you want to preserve some data after the page is closed and reloaded - so maybe you don't really need it?