Access the iframe URL from the Chrome extension

I have an extension that needs to load a page with a lot of redirects on its background page. After this page gets to a well-known URL ( https://website.com/index.php ), iframe should have its src for about:blank .

The last page is quite large and has large images and everything that does not need to be loaded, so instead of joining the iframe onload , I installed the following function on an interval of 100 ms:

 function update(){ if(document.getElementsByTagName('iframe')[0].contentDocument.location.href == "https://website.com/index.php"){ console.log("Done!"); clearInterval(updateInterval); document.getElementsByTagName('iframe')[0].src = "about:blank"; } } 

However, as soon as the iframe starts loading, update () throws this error:

An unsafe JavaScript attempt to access a frame with the URL https://website.com/index.php from a frame with the URL chrome extension: //hdmnoclbamhajcoblymcnloeoedkhfon/background.html. Access request to frames has the protocol "chrome-extension", access to the frame has the protocol "https". Protocols must comply.

I tried catch () with this error, but the message sent back to Javascript unsurprisingly does not include the URL. The page is redirected several times, so it’s important to know the exact URL. The src iframe property is also not updated to reflect redirects.

+7
source share
1 answer

After many Googling and almost giving up, I came up with the following solution. It uses the entered content script to send a message back to the extension after loading the correct page.

manifest.json:

 { ... "background": { "page": "background.html" }, "content_scripts": [ { "matches": ["http://website.com/index.php"], "js": ["content.js"], "all_frames": true, "run_at": "document_start" } ], "permissions": [ "*://*.website.com/*" ] } 

background.html:

 <html> <head> <script type="text/javascript" src="background.js"></script> </head> <body> <iframe src="about:blank"></iframe> </body> </html> 

background.js:

 var waiting = false; function login(){ // Call this function to start var frame = document.getElementsByTagName('iframe')[0]; frame.src = "https://website.com/login/"; waiting = true; } function callback(){ // This gets called once the page loads console.log("Done!"); } chrome.extension.onMessage.addListener(function(request, sender, sendResponse){ if(request.loaded && waiting){ // If you used a pattern, do extra checks here: // if(request.loaded == "https://website.com/index.php") document.getElementsByTagName('iframe')[0].src = "about:blank"; waiting = false; callback(); } }); 

content.js:

 chrome.extension.sendMessage({loaded: window.location.href}); 
+8
source

All Articles